Last updated

Permanently redirect WordPress pages

After my trip to Mephisto some time back, I noticed that some pages were accessible from different URLs. After moving back to WordPress, these permalinks no longer work.

I’m running WordPress with Apache2, so it shouldn’t be too hard redirect those old permalinks to their new locations. (That’s what rewriting is all about anyway).

Here is the default .htaccess file generated by WordPress:

 1# BEGIN WordPress
 2<IfModule mod_rewrite.c>
 3RewriteEngine On
 4RewriteBase /
 5RewriteCond %{REQUEST_FILENAME} !-f
 6RewriteCond %{REQUEST_FILENAME} !-d
 7RewriteRule . /index.php [L]
 8</IfModule>
 9
10# END WordPress

As I said, it’s generated by WordPress. It would be very unwise to edit this, because our changes might get lost in the future.

The solution is simple. Add another block above the generated one that does permanent redirects. In this example I rewrite pages/svnsheet to http://ariejan.net/svncheatsheet.

 1<IfModule mod_rewrite.c>
 2RewriteEngine On
 3RewriteBase /
 4RewriteCond %{REQUEST_FILENAME} !-f
 5RewriteCond %{REQUEST_FILENAME} !-d
 6RewriteRule ^pages/svnsheet$ http://ariejan.net/svncheatsheet [R=301,L]
 7</IfModule>
 8
 9# BEGIN WordPress
10<IfModule mod_rewrite.c>
11RewriteEngine On
12RewriteBase /
13RewriteCond %{REQUEST_FILENAME} !-f
14RewriteCond %{REQUEST_FILENAME} !-d
15RewriteRule . /index.php [L]
16</IfModule>
17
18# END WordPress

FYI, the R=301 means the browser (or search bot) receives a “Moved Permanently” message. L means this is the last rewrite rule to read.

Of course, you can go nuts and add all sorts of funky regular expressions to rewrite URLs.

The nice thing is that WordPress will only replaces the block between the BEGIN and END tags, keeping your rewrites in tact.

Note: don’t forget to restart apache if your rewrites don’t seem to work.