【问题标题】:Apache - remove .php and .html file extensions using mod_rewrite in httpd.confApache - 使用 httpd.conf 中的 mod_rewrite 删除 .php 和 .html 文件扩展名
【发布时间】:2022-03-25 08:20:30
【问题描述】:

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

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

<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 文件扩展名的 url 时,我得到一个 404!为什么这不起作用?

【问题讨论】:

    标签: apache mod-rewrite httpd.conf


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      <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>
      

      【讨论】:

        【解决方案3】:

        是的,我花了 2 个小时尝试一切,直到我删除了 $1 上的前导斜杠(即“$1”而不是“/$1”),然后一切正常。与另一位用户的评论相反。虽然我确实需要 RewriteRule 正则表达式中的斜杠来匹配请求的文件名,但在我将其更改为“^(.*)$”并首先使用 RewriteCond 进行测试之前。

        【讨论】:

          猜你喜欢
          • 2015-06-29
          • 2019-02-12
          • 2018-10-10
          • 2013-10-11
          • 1970-01-01
          • 2014-03-04
          • 1970-01-01
          • 1970-01-01
          • 2010-12-31
          相关资源
          最近更新 更多