【问题标题】:.htaccess mod_rewrite with encoded URL path not working while unencoded path works.htaccess mod_rewrite 编码的 URL 路径不工作,而未编码的路径工作
【发布时间】:2019-01-19 11:39:54
【问题描述】:

我是在 apache 上使用 mod_rewrite 的新手,我目前正在尝试编写一个 url-shortener,它采用像 mydomain/s/short/{UriToShorten} 这样的 URL 并缩短给定的 URI。

会发生什么强>
当我在浏览器中将 URI 传递给缩短路径时,例如 localhost/s/short/http://example.com ,将调用脚本 highlight.php 并且缩短过程按预期工作。但是,如果我对 URL-Component 进行编码并传递像 localhost/s/short/http%3A%2F%2Fexample.com 这样的 URI(这应该是正确的用法),我会收到消息

未找到
在此服务器上找不到请求的 URL /s/short/http://example.com

调试表明,shortcut.php 或 index.php 都没有运行(所以我相信,服务器确实尝试搜索 short 的子目录 http:)。这似乎在斜杠编码 %2F 所在的位置独立发生。


预期结果
我希望编码版本可以工作,并且可能未编码的 URI 会导致错误(因为 URL 编码是为了避免这些错误而专门进行的)。

我使用什么
我将以下内容用作 .htaccess:

RewriteEngine On
RewriteBase /s/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^short/(.*)$ shorten.php?url=$1 [L,NC]
RewriteRule ^([a-z0-9]{5})$ index.php?slug=$1 [L,NC]

我的文件夹结构是:

-www
  -s
    -.htaccess
    -shorten.php
    -index.php

我的 Apache 版本是 Apache/2.4.33

我尝试了什么
由于我不知道为什么会发生这种情况,我只能搜索 mod_rewrite 文档并尝试添加 [NE] Flag,这显然不起作用。

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    这是因为 Apache 在默认情况下会阻止编码的斜杠。从 Apache 2 开始,可以允许它们: https://httpd.apache.org/docs/2.4/mod/core.html#allowencodedslashes

    但是,设置AllowEncodedSlashes On 时要小心。这是 Apache 制定的一项安全措施。

    如果路径信息中需要编码斜杠,强烈建议使用 NoDecode 作为安全措施。允许对斜线进行解码可能会导致不安全的路径。

    如果要启用编码斜杠,请改用AllowEncodedSlashes NoDecode。例如:

    <VirtualHost *:80>
      [...]
    
      AllowEncodedSlashes NoDecode
    
    </VirtualHost>
    

    【讨论】:

      【解决方案2】:

      好的,我找到了导致问题的原因:

      该错误并非发生在每个编码的 url 字符上,但总是在 URL 包含 %2F 时发生。所以我的问题似乎是this SO question about encoded Slashes

      我需要在httpd.conf 中设置AllowEncodedSlashes NoDecode(或打开)ANDhttpd-vhosts.conf 中才能正常工作。

      经验教训:始终检查 httpd.conf-features 并明确打开您希望默认打开的功能

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-27
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        • 1970-01-01
        • 2013-07-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多