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

I have a site with a set of old .html and .php pages that were placed in the CMS.

There are currently about 30 mod_alias redirects in the .htaccess file 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 , therefore it also has the following:

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

Currently both are used together, resulting in:

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

How to apply the rewrite rule only if the redirection operators 301 mod_alias were not met, so the following happens:

http://www.example.com/oldpage1.html → redirect to → http://www.example.com/newpage1.php →, which is processed as → http://www.example.com/index.php?page=/newpage1.php

Any hints would be greatly appreciated? Thanks.

+7
source share
1 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 placement order in .htaccess. This corresponds to the order required for this situation.

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

Complete solution:

 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 
+10
source

All Articles