Mod_rewrite适用于localhost,但不适用于服务器

时间:2014-06-20 16:48:18

标签: apache .htaccess mod-rewrite centos httpd.conf

这不是一个寻找解决方案的问题,而是一个寻求澄清的问题。

几天前,我在使用localhost(运行XAMPP)在我的生产服务器(CentOs 6 LAMP堆栈)上工作时,我的mod_rewrites工作得很好。

重写看起来像这样:

RewriteEngine On
RewriteBase /

RewriteRule ^my/page/([a-zA-Z0-9]+)$ /my/page/$1/
RewriteRule ^my/page/([a-zA-Z0-9]+)/$ /my_page.php?t=$1

在localhost上,上述行完美运行并执行以下操作:

my/page/ab123 --> my_page?t=123

但是,在我的生产服务器上,上述规则无效。我一般都对mod_rewrites和服务器架构非常陌生,所以找到解决方案花了我几个小时。现在,我很想知道为什么以下问题解决了我的问题,因为我老老实实地没有任何线索。

RewriteEngine On
RewriteBase /

RewriteRule ^/my/page/([a-zA-Z0-9]+)$ /my/page/$1/
RewriteRule ^/my/page/([a-zA-Z0-9]+)/$ /my_page.php?t=$1

这是一个简单的改变。我必须在页面名称之前添加正斜杠:^/my/page

我希望能够将我的htaccess文件移动到我的服务器,而不必总是添加这个额外的字符。有办法解决这个问题吗?

此外,我的httpd.conf文件

中会显示以下选项
<Directory /my/sites/directory> 
        Options -Indexes +Multiviews +FollowSymLinks
        DirectoryIndex index.php index.html
        AllowOverride All
        Allow from all
</Directory>

1 个答案:

答案 0 :(得分:0)

根据规则的上下文,需要或不需要前导斜杠。如果规则位于htaccess文件(或每个目录上下文)中,则不需要前导斜杠。如果规则在server / vhost配置中,那么您需要一个前导斜杠。如果apache的版本低于v2.2(或2.0,不记得),那么你总是需要前导斜杠。

如果你这样做可能会更好:

RewriteEngine On
RewriteBase /

RewriteRule ^/?my/page/([a-zA-Z0-9]+)/?$ /my_page.php?t=$1

这将使前导斜杠和尾随斜杠成为可选。