WordPress .htaccess and Permalink Cheat Sheet

WordPress is still incredibly popular and sometimes you have a to move a WordPress installation or you want to change your permalink structure. Regardless of your motivation, you probably don't want to hurt your SEO.

I've spent some time writing and testing .htaccess for Apache2 redirects recently, so I thought I'd share a list of commonly needed WordPress redirects using regular expressions or just removing segments.

By default I'll assume you use a .htaccess file that looks something like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# Additional rewrite rules go here

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Let's say you are combining your blog with your main website or you are merging another blog into yours, these would be perfect scenarios for making your WordPress find the posts associated with links that it usually wouldn't know about, because they're in another pattern.

In most of the below recipes we'll use a Regular Expression with a capture group for the incoming hit. Every capture group will be available to us for the redirect destination, starting at $1 and then $2 and so on.

Rewrite from Subfolder to Root

When moving a WordPress installation from a sub-folder to the web root, you'll want to redirect all hits that previously went to your sub-folder, maybe /blog/ to the web root /.

RewriteRule ^blog/(.*)$ /$1 [R=301,L]

Renamed Page or Post, Redirect Previous URL

Redirect 301 "/old-page-name" "/new-page-name"

301 is the HTTP status code for "moved permanently".

Permalinks: Date (Day, Month and Name) to Post Name

Assuming that the previous post format included year and month kind of like this: /2017/12/31/postname-here.

RewriteRule ^[0-9]{4}/[0-9]{2}/[0-9]{2}/(.*)$ /$1 [R=301,L]

Permalinks: Date (Month and Name) to Post Name

Assuming that the previous post format included year and month kind of like this: /2017/12/postname-here.

RewriteRule ^[0-9]{4}/[0-9]{2}/(.*)$ /$1 [R=301,L]

Combinations

Obviously all of these can be combined:

RewriteRule ^blog/[0-9]{4}/[0-9]{2}/(.*)$ /$1 [R=301,L]

Writing your own .htaccess Rewrite Rules

When writing your own rewrite rules, keep in mind that the Apache regex engine is slightly different than most used in programming languages. Most importantly: /, the slash, does not need to be escaped, because it does not delimit the regex.

If you want to test a lot of regexes at once or if you have some very specific URLs or patterns that you need to redirect, you can make use of a regex tester like Regex101. It will allow you to test a lot of things ahead of time, you just need to fix the escaped slashes afterwards.

Tagged with: #.htaccess #apache2 #WordPress

Thank you for reading! If you have any comments, additions or questions, please tweet or toot them at me!