【问题标题】:Apache mod_rewrite Returning Bad Request in WAMPServerApache mod_rewrite 在 WAMPServer 中返回错误请求
【发布时间】:2011-02-26 15:49:13
【问题描述】:

我正在使用 WAMPServer 2.1 运行 Windows 7 64 位。运行的 Apache 版本是 2.2.17。我正在尝试在httpd.conf 中设置一个简单的重写规则:

<IfModule rewrite_module>
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [PT,QSA,L]
</IfModule>

我之前已经获得了更简单的 RewriteRules 来工作,无需正则表达式、重写表达式等。然而,在这一点上,当此规则处于活动状态时,每当尝试访问任何 URL 时,我都会收到 400 Bad Request 错误。每当发生这种情况时,Apache 日志文件都会给出这些错误:

[Sat Feb 26 10:24:18 2011] [error] [client 127.0.0.1] Invalid URI in request GET /index.php HTTP/1.1
[Sat Feb 26 10:24:21 2011] [error] [client 127.0.0.1] Invalid URI in request GET / HTTP/1.1

我尝试点击localhost/index.php 的第一个错误。第二个我刚试过localhost

此外,即使我使用了更简单的规则,RewriteCond 行似乎也不起作用:静态的现有文件(例如 style.css)无论如何都被重新路由。

启用 RewriteLogging 似乎会使 Apache 崩溃,这似乎是 documented issue on 64-bit machines running Windows 7。关于问题可能是什么的任何想法?

【问题讨论】:

    标签: php apache mod-rewrite wamp wampserver


    【解决方案1】:

    这里有两个问题可能会导致您遇到麻烦。首先,您无法在服务器上下文中如此轻松地检查文件是否存在(就像使用 httpd.conf 一样),因为请求尚未映射到文件系统。

    如果您对静态资源的请求恰好与您的 DOCUMENT_ROOT 之外的文件系统结构直接对应,您可以通过在传入的 REQUEST_URI 之前附加 DOCUMENT_ROOT 的值来解决此问题,如下所示:

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
    

    如果静态资源的路径在某处被转换,mod_rewrite documentation 建议使用以下内容,这将发出一个子请求以根据请求 URI 执行前瞻:

    RewriteCond %{LA-U:REQUEST_FILENAME} !-f
    RewriteCond %{LA-U:REQUEST_FILENAME} !-d
    

    虽然这种方法比较昂贵,所以尽量使用第一种方法。

    其次,您传回请求的 URI 实际上是无效的,因为它需要前导斜杠。更正它并将其与上面的新条件相结合,为您提供了这个修改后的规则集:

    RewriteEngine On
    
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
    RewriteRule ^.*$ /index.php?page=$0 [PT,QSA,L]
    

    注意这里page的值总是有一个前导斜杠,所以你可能真的想使用这个规则,这取决于你在index.php中的处理逻辑:

    RewriteRule ^/(.*)$ /index.php?page=$1 [PT,QSA,L]
    

    【讨论】:

    • 这似乎是问题所在。此外,我最终不得不使用您在底部的修改后的重写规则(在匹配的正则表达式中使用/),因为其他模式仍然给我来自浏览器的 400 Bad Request 错误(并且 Invalid Get 在apache 日志)。
    【解决方案2】:

    你试过设置

    RewriteBase /your_directory

    变量?

    【讨论】:

    • 是的。 RewriteBase 导致 Apache 根本无法启动,并出现错误 RewriteBase: only valid in per-directory config files(我正在使用 httpd.conf)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2014-04-07
    • 2012-11-27
    • 2019-07-28
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多