Skip to main content

Permanently redirect WordPress pages

·249 words·2 mins· ·
General Wordpress Apache Apache2 Rewrite Mod_rewrite Permalinks
Ariejan de Vroom
Author
Ariejan de Vroom
Jack of all Trades, Professional Software Craftsman

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:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# 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.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^pages/svnsheet$ http://ariejan.net/svncheatsheet [R=301,L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# 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.

Related

Here we go again: WordPress 2.5
·200 words·1 min
General Wordpress Updates
Wordpress 2.3 released!
·103 words·1 min
General Wordpress Blog Releases
Wordpress Plugin: AutoFlickr 1.0
·219 words·2 mins
General Wordpress Features AutoFlickr