1 August 06

Redirecting two ways at once with mod_rewrite

It’s easy to redirect visitors to a different page and it’s easy to show a certain page based on a certain URL. But it’s a bit more difficult to do both at the same time.

I received an email from John at Media Surgery asking how to redirect users coming to sites through old links to the new links, but still show the old page. He had read my .net article on mod_rewrite, but I’ll be the first to admit, I’m no mod_rewrite expert. My first thought was easy! Just redirect, then show old page. But it doesn’t work – it just loops endlessly (or at least until Firefox stops the looping). Each line of my code was working separately but together… nope.

After about an hour of research (I hate getting things wrong), I found the answer, and it worked perfectly. As the code seemed pretty rare, I thought I’d share it with everyone.

RewriteEngine On
// test.php redirecting to test/
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([a-zA-Z0-9]+)\.php$ $1/ [R=301,L]
// test/ fetching test.php
RewriteRule ^([a-zA-Z0-9]+)/?$ $1.php [QSA,L]

[Remove all lines starting with // – they’re just comments and Txp won’t let me having normal Apache ’#’ comments]

The %{ENV:REDIRECT_STATUS} checks if it is an internal subrequest and passes the following rule.

So there we have it, if we go to ‘test.php’ or ‘test/’ or ‘test’, we will get the same page on the fileserver under ‘test.php’

Enjoy this? Subscribe to the feed for the very latest updates.

Back to top — © Rik Lomas 2006-2008 all rights reserved.
No part may be reproduced without the written permission of the copyright owner, unless otherwise stated