How to have a load of redirect rules end with a ru

2019-09-02 14:03发布

问题:

What is required

  1. oldwebsite.com/about and oldwebsite.com/about/ go to newwebsite.com/about
  2. oldwebsite.com and oldwebsite.com/ go to newwebsite.com
  3. oldwebsite.com/wp-admin stays as it is as I need to access the wordpress admin backend
  4. oldwebsite.com/everything-else go to newwebsite.com/blog/everything-else

What I tried

I used Redirect 301 ... for 1st 2 requirements.

They work well.

What happened

Then when I added

RewriteRule !^wp-admin($|/) http://newwebsite.com/blog%{REQUEST_URI} [L,R=301]

from elsewhere for 3 and 4

It doesn't work when I tried to access wp-admin as I get redirected to newwebsite.com/blog/wp-login.php......

回答1:

Key point 1

I should use L flag to ensure that once a rule matches, it will exit from the htaccess.

Key point 2

WordPress relies on a lot of files and subfolders for backend. Need to use the regular expression (wp\-.*) to catch all scenarios.

Code with comments

# when whatever comes after oldwebsite.com/ matches about OR about/
# go to ...
# the L makes sure once this rule matches, stop checking the rest.
# the 301 is for the redirection status code which is good for SEO 
# read https://moz.com/learn/seo/redirection
RewriteRule ^about($|/) http://newwebsite.com/about [R=301,L]

# same treatment for the index page
RewriteRule ^($|/) http://newwebsite.com [R=301,L]

# when whatever comes after oldwebsite.com/ AND does NOT match wp-{wildcard here....}
# take that whatever and append to http://newwebsite.com/blog/
# and then redirect there using status code 301 and if this rule is true, stop any further
RewriteRule !^(wp\-.*) http://newwebsite.com/blog%{REQUEST_URI} [R=301,L]