【问题标题】:htaccess RewriteRule seems to be correct but not workinghtaccess RewriteRule 似乎是正确的但不起作用
【发布时间】:2011-08-18 04:13:05
【问题描述】:

我想将所有访问任何 .php 文件的流量重定向到 index.php。

例如:
domain.com/test.php
domain.com/test/test.php
.. 应该去 domain.com/index.php。相似地:
www.domain.com/test.php
www.domain.com/test/test.php
.. 应该去 www.domain.com/index.php。

我添加了以下规则:

RewriteRule (..com)(/.)?/(.*.php) $1/index.php

根据在线正则表达式测试器应该会给我正确的结果,但是当我在实际的 htaccess 上使用它时,规则似乎被忽略了,而是给出了 404 错误。

我究竟做错了什么?

【问题讨论】:

    标签: .htaccess rewrite


    【解决方案1】:

    RewriteRule 的第一个参数与主机不匹配。请尝试以下操作:

    RewriteEngine on
    
    RewriteCond %{REQUEST_URI} index.php$
    RewriteCond %{QUERY_STRING} arg=something
    RewriteRule \.php$ /index.php? [R]
    
    RewriteCond %{REQUEST_URI} !index\.php$
    RewriteRule \.php$ /index.php? [R]
    

    希望对您有所帮助。

    【讨论】:

    • 感谢您的帮助,但不幸的是它仍然不起作用,它只是带来了404错误而不是重定向到index.php。
    • 知道为什么会这样吗?或者如果我应该采取任何其他方法?
    • 您的 index.php 文件是否进行任何类型的重定向,或者您的 .htaccess 中是否有其他规则?该规则应该有效,您是否有权访问主 apache 配置以打开 RewriteLog,否则您是否确认已启用 mod_rewrite?此外,我添加了一个条件来避免我昨晚忘记的重定向循环以及检查index.php 上的查询字符串参数的规则。
    • 此外,规则上的尾随 ? 会删除查询字符串,如果您希望通过重定向维护它们,只需删除 ?
    【解决方案2】:

    试试这个代码:

    Options +FollowSymlinks -MultiViews
    RewriteEngine on
    
    # internally redirect all .php files to index.php
    RewriteCond %{REQUEST_URI} !^/+index\.php [NC]
    RewriteRule \.php$ /index.php? [L,NC]
    
    # remove all query string from /index.php
    RewriteCond %{QUERY_STRING} !^$
    RewriteRule ^index\.php$ /index.php? [L,R]
    

    【讨论】:

    • 您好,感谢您的建议,但不幸的是,它只返回 404 错误,而不是实际重写 URL 以转到 index.php。任何想法为什么会这样?我还有一堆垃圾邮件程序块和 IP 块,它们也不起作用。他们有关系吗?
    • 很可能是这样。我建议请查看您的 access.log 以了解为什么要加载此 URL。
    • 您也可以从我上面的答案中再次复制/粘贴代码。我做了一个小修改。
    • 嗨,anubhava,再次感谢您的建议。该页面仍然返回 404 错误。这个mod的原因是因为我们的网站最近被黑了,我试图将404请求重定向到以前的垃圾邮件php文件到index.php。我也想做例如/index.php?arg=something,也返回 index.php,但我不知道该怎么做。非常感谢您的帮助。
    • 抱歉回复晚了,已经很晚了,不得不去睡觉了。我刚刚按照您的要求编辑了上面的答案,以 discard 所有来自 /index.php 的查询字符串。
    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多