Using mod_rewrite and mod_alias (redirect 301) together in .htaccess?

7.4k views Asked by At

I have a site with a set of old .html and .php pages that have been put into a CMS.

Currently in the .htaccess file there are about 30 mod_alias redirects in the following form:

redirect 301 /oldpage1.html http://www.example.com/newpage1.php
redirect 301 /oldpage2.php http://www.example.com/newpage2.php
redirect 301 /oldpage3.php http://www.example.com/newpage3.php

But we want to use mod_rewrite to have pretty URLs in our CMS, which will take the form http://www.example.com/pagename.php, so also have the following:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1

At the moment both are being applied together, which results in:

http://www.example.com/newpage1.php?page=oldpage1.html

How can I apply the rewrite rule only when no match has been made by the mod_alias redirect 301 statements, so that the following occurs:

http://www.example.com/oldpage1.html -> redirects to -> http://www.example.com/newpage1.php -> which is treated as -> http://www.example.com/index.php?page=/newpage1.php

Any hints would be very much appreciated? Thanks.

1

There are 1 answers

0
Nick Evans On BEST ANSWER

I found the answer in a great explanation of mod_rewrite and mod_alias

The problem is that mod_rewrite always occurs before mod_alias, regardless of the order the are placed in .htaccess. This is the reverse of the order required for this situation.

The trick is to use RewriteRule [R=301] instead of redirect 301, and hence use mod_rewrite for everything instead of mixing it with mod_alias.

Full solution is as follows:

RewriteEngine on
RewriteBase /

RewriteRule ^oldpage1.html /newpage1.php [R=301,L]
RewriteRule ^oldpage2.php /newpage2.php [R=301,L]
RewriteRule ^oldpage3.php /newpage3.php [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1