Apache - 使用httpd.conf中的mod_rewrite删除.php和.html文件扩展名

时间:2017-02-21 23:18:18

标签: apache mod-rewrite httpd.conf

在Ubuntu 14.04上运行Apache 2。 rewrite_module已启用(sudo apachectl -M)。

在/etc/apache2/apache2.conf(httpd.conf的Ubuntu版本)中我有以下代码块:

<Directory /var/www/>
    <IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteCond /%{REQUEST_FILENAME}.php -f
        RewriteRule ^([a-zA-Z0-9_-\s]+)/$ /$1.php

        RewriteCond /%{REQUEST_FILENAME}.html -f
        RewriteRule ^([a-zA-Z0-9_-\s]+)/$ /$1.html
    </IfModule>

    <IfModule mod_expires.c>
        ...

        <IfModule mod_headers.c>
            ...
        </IfModule>
    </IfModule>
</Directory>

sudo service apache2 restart

当我在没有.php文件扩展名的服务器上访问网址时,我得到了404!为什么这不起作用?

2 个答案:

答案 0 :(得分:0)

您的规则适用于我 htaccess 上下文。但是当我将这些规则添加到 serverConfig 上下文时,服务器返回了404未找到的。实际上问题是在serverConfig上下文需要RewriteRule模式中的前导斜杠。因此,您需要在Rule的模式中添加一个前导斜杠:

RewriteRule ^/([a-zA-Z0-9_-\s]+)/?$ /$1.php

答案 1 :(得分:0)

我终于明白了。对我有用的是:

<Directory /var/www/>
    <IfModule mod_rewrite.c>
        RewriteEngine On

        RewriteCond %{REQUEST_FILENAME}.php -f
        RewriteRule ^(.*)$ $1.php [L]

        RewriteCond %{REQUEST_FILENAME}.html -f
        RewriteRule ^(.*)$ $1.html [L]
    </IfModule>

    <IfModule mod_expires.c>
        ...

        <IfModule mod_headers.c>
            ...
        </IfModule>
    </IfModule>
</Directory>