3

I'm helping to move a WordPress site from one domain to another, which includes a change in permalink structure. I know I can use a .htaccess entry, but I'm not that well-versed (yet) in regular expressions.

I need to change this:

http://www.oldwebsite.com/2013/09/title-of-post.html

to this:

http://www.newwebsite.com/title-of-post

dropping the year, month, and .html from every URL.

1 Answer 1

2

I’ve done this with Apache mod_rewrite and it works great. Just add these three lines to either the .htaccess or Apache2 configuration on the old server. This should work well/cover all .html files as well as other variations:

RewriteEngine on
RewriteBase /
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /([^\ ]+)\.html
RewriteRule ^([0-9]{4})/([0-9]{2})/([^\ ]+)\.html?$ http://www.newwebsite.com/$3 [L,R=301]
RewriteRule ^([0-9]{4})/([^\ ]+)\.html?$ http://www.newwebsite.com/$2 [L,R=301]
RewriteRule ^([0-9]{4})/([0-9]{2})/?$ http://www.newwebsite.com/ [NC,L,R=301]
RewriteRule ^([0-9]{4})/?$ http://www.newwebsite.com/ [NC,L,R=301]
RewriteRule ^(.*)$ http://www.newwebsite.com/$1 [NC,L,R=301]

So the first two RewriteRule entries handle requests to the following URLs:

http://www.oldwebsite.com/2013/04/test.html 
http://www.oldwebsite.com/2013/test.html 

And now send them to:

http://www.newwebsite.com/test

The next two RewriteRule entries handle requests to these directory level root URLs:

http://www.oldwebsite.com/2013/04/
http://www.oldwebsite.com/2013/

To this the base URL of your site:

http://www.newwebsite.com/

And the last RewriteRule is set to grab any other URLs that don’t fit the above criteria and send them to the main URL while passing the full param.

I would suggest that you test these out using curl -I like so:

curl -I http://www.oldwebsite.com/2013/04/test.html

That will show you the Apache header output & tell you exactly where pages are being redirected without having to deal with a full web browser headaches when debugging stuff like this.

1
  • 2
    It's great that you explained each part so users can learn from your answer!
    – dan
    Nov 21, 2013 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.