301重定向正则表达式优化需求:排除含/category/路径的页面不执行指定重定向
Fixing Your 301 Redirect to Exclude /category/ Paths
Got it, let's sort out this redirect issue for you. The problem with your current regex is that it doesn't account for paths that include /category/ before the /the-magazine/ segment—so it's matching both your target page and the category page you want to exclude.
Modified Regex Rule
Here's the updated source URL regex that will skip any path containing /category/:
^(?!.*\/category\/)\/the-magazine\/2012-springsummer-issue\/([A-Za-z].*)
How It Works
Let's break down the key additions:
^: Anchors the match to the start of the URL path, ensuring we check the entire path from the beginning.(?!.*\/category\/): This is a negative lookahead assertion. It tells the regex engine: "If the path contains/category/anywhere, do NOT match this rule." The.*allows any characters before or after/category/, so it catches paths where/category/is at the start (like your page 2) or anywhere else in the URL.- The rest of the regex (
\/the-magazine\/2012-springsummer-issue\/([A-Za-z].*)) stays the same—it still captures the trailing part of the URL to use in your target$1variable.
Test It Out
- For your page 1 (
/the-magazine/2012-springsummer-issue/about-last-night-event-planning/): The path doesn't include/category/, so the regex matches, and it redirects tohttps://www.example.com/article/about-last-night-event-planning/as intended. - For your page 2 (
/category/the-magazine/2012-springsummer-issue): The path has/category/, so the negative lookahead kicks in, and this rule won't apply—no unwanted redirect here.
Quick Note for Server Configs
If you're using this in Apache (mod_rewrite) or Nginx, make sure your server supports PCRE (Perl Compatible Regular Expressions)—most modern servers do by default.
- For Apache, you might wrap this in a
RewriteRule(note Apache strips the leading/from the path, so we remove it from the regex):RewriteRule ^(?!.*\/category\/)the-magazine\/2012-springsummer-issue\/([A-Za-z].*) https://www.example.com/article/$1 [R=301,L] - For Nginx, the syntax would look something like:
rewrite ^(?!.*\/category\/)\/the-magazine\/2012-springsummer-issue\/([A-Za-z].*) https://www.example.com/article/$1 permanent;
内容的提问来源于stack exchange,提问作者Sujan Shrestha
相关产品推荐
相关产品推荐

