求助:基于.htaccess正则实现多域名301重定向规则配置
Hey Andy, I feel your pain—manually setting up hundreds of 301 redirects is no fun at all. Good call reaching for regex and mod_rewrite to simplify this. Here's a set of rules that'll handle all your cases in one go, ordered correctly to make sure everything matches as intended:
First, make sure mod_rewrite is enabled (you probably already have this since you're using RewriteRule, but just in case):
RewriteEngine On
Step 1: Exclude the contact and main-menu pages
These pages won't be redirected—they'll stay on your old domain. The [L] flag tells Apache to stop processing further rules once this matches:
# Skip redirect for contact page (works with or without trailing slash) RewriteRule ^contact/?$ - [L] # Skip redirect for main-menu page (works with or without trailing slash) RewriteRule ^main-menu/?$ - [L]
Step 2: Redirect all /tb- prefixed URLs to sheepdog-training.com
This rule captures everything after tb- and appends it to the new domain, keeping the original path intact:
RewriteRule ^tb-(.*)$ http://sheepdog-training.com/tb-$1 [R=301,L]
^tb-(.*)$: Regex that matches any URL starting withtb-, capturing the rest of the path into the variable$1[R=301,L]: Sends a permanent 301 redirect and stops processing other rules for this request
Step 3: Redirect all remaining URLs to theworkingsheepdog.com
This catches every path that wasn't matched by the previous rules, redirecting to the new domain with the exact same path:
RewriteRule ^(.*)$ http://theworkingsheepdog.com/$1 [R=301,L]
Quick Tips:
- Rule order is critical: We handle exceptions first, then the
/tb-specific redirect, then the catch-all. If we reversed the order, the catch-all would match everything before the/tb-rule ever runs. - Test with 302 first: Before locking in
R=301, useR=302(temporary redirect) to verify all paths redirect correctly. Browsers cache 301s aggressively, so testing with 302 avoids stuck cache headaches. - Adjust trailing slashes: The
/?in the exception rules handles bothcontactandcontact/—remove the/?if you only want to match one format.
内容的提问来源于stack exchange,提问作者Andy Nickless

