Using Apache mod_rewrite to redirect old URLs

Apache LogoThere are lots of examples and tutorials covering Apache and mod_rewrite, but generally they address the problem where you want to map a ‘nice’ url to your script. For example:

http://example.com/products/kitchen/cutlery

to

http://example.com/products.php?category=kitchen&sub-category=cutlery

is easily achieved with the following .htaccess rules:

[cc lang=’apache’ line_numbers=’false’]RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/? /one.php?action=$1&category=$2&subcategory=$3 [L][/cc]

However if you want to rewrite in the other direction it might not be immediately obvious that you cannot use rewrite rules with your GET URL variables. So if you want to go from

http://example.com/products.php?category=kitchen&sub-category=cutlery

to

http://example.com/products/kitchen/cutlery

you need to sniff the query variables as well as the script name.

[cc lang=’apache’ line_numbers=’false’]
RewriteCond %{QUERY_STRING} ^action=([A-Za-z0-9-]+)&category=([a-zA-Z0-9]+)&subcategory=([a-zA-Z0-9]+)
RewriteRule ^two.php /%1/%2/%3/? [R=301,L]
[/cc]

The rewrite condition only looks at the query string. If the condition is met, then the rewrite rule is applied. The ‘R=301’ tells the browser that that is a permanent redirect and the ‘L’ tells Apache that it is done rewriting.

To test/play/not-take-my-word-for-it:

(This assumes you are operating from the web root of http://example.com/.)

Create one.php and two.php with the following contents:

[cc lang=’php’ line_numbers=’false’]< ?php echo 'Filename: '.__FILE__.'


‘;
echo ‘$_GET:
‘;
echo ‘

';
        echo print_r(var_export($_GET),1);

?>[/cc]

Create an .htaccess file as follows:

[cc lang='apache' line_numbers='false']RewriteEngine On

RewriteBase /

# assumes you are using letters, digits and hyphens in your get variables

# rewrite two.php?action=something&category=and&subcategory=anotherthing to /something/and/anotherthing

RewriteCond %{QUERY_STRING} ^action=([A-Za-z0-9-]+)&category=([a-zA-Z0-9]+)&subcategory=([a-zA-Z0-9]+)

RewriteRule ^two.php /%1/%2/%3/? [R=301,L]

# rewrite something/and/anotherthing to one.php

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/? /one.php?action=$1&category=$2&subcategory=$3 [L][/cc]
Upload them all to your web root and try:
http://example.com/one/two/three

and

two.php?action=one&category=two&subcategory=three
Tagged with: , , ,
Posted in Servers, Tech Blog, Web

Leave a Reply

Your email address will not be published. Required fields are marked *

*