在.htaccess中一起使用mod_rewrite和mod_alias(重定向301)?

时间:2011-01-31 21:14:33

标签: .htaccess mod-rewrite redirect mod-alias

我的网站上有一组旧的.html和.php页面已放入CMS。

目前在.htaccess文件中有大约30个mod_alias重定向,格式如下:

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

但是我们希望使用mod_rewrite在我们的CMS中拥有漂亮的网址,其格式为http://www.example.com/pagename.php,所以还有以下内容:

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

目前两者正在一起使用,结果是:

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

如果mod_alias重定向301语句未匹配,如何应用重写规则,以便发生以下情况:

http://www.example.com/oldpage1.html - >重定向到 - > http://www.example.com/newpage1.php - >被视为 - > http://www.example.com/index.php?page=/newpage1.php

任何提示都会非常感激吗?感谢。

1 个答案:

答案 0 :(得分:11)

我在great explanation of mod_rewrite and mod_alias找到了答案

问题是mod_rewrite总是在mod_alias之前发生,无论它放在.htaccess中的顺序如何。这与此情况所需的顺序相反。

诀窍是使用RewriteRule [R=301]代替redirect 301,因此将mod_rewrite用于所有内容,而不是将其与mod_alias混合使用。

完整的解决方案如下:

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
相关问题