【问题标题】:Prevent rules conflicts with htaccess' RewriteRule防止与 htaccess 的 RewriteRule 发生规则冲突
【发布时间】:2014-10-08 16:25:07
【问题描述】:

我想用一些RewriteRules 来改造:

这里是htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?id=$1 [L]
RewriteRule ^(.*)/(.*)$ /index.php?id=$2&user=$1 [L]
</IfModule>

但似乎最后两条规则不兼容:有了这个htaccess,我得到了一些500 Internal Server Error

如何创建两个规则以使它们不会“重叠”?

注意事项:

  • 这两条规则中的每一条都单独起作用

  • 当我使用第二条规则时,http://example.com/someone/blah => index.php?id=blah&amp;user=someone 有效,但似乎根文件夹不再是 //someone/ 然后 CSS 不是找到...如何防止在这种情况下更改基本文件夹?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    您有 4 个问题:

    1. 您的第一条规则(.*) 会将任何内容转换为/index.php?id=$1
    2. 您的第二条规则不会验证文件或文件夹是否存在,并且可能会陷入导致500 internal server error 的无限循环。
    3. 规则的顺序
    4. 您正在使用相对路径来提供 CSS 和图像,这导致它无法使用您的 URL 格式,例如 domain.com/anything/anything

    要解决重定向问题,您可以使用:

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
    
        RewriteRule ^index\.php$ - [L]
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^([^/]+)/([^/]+)$ /index.php?id=$2&user=$1 [L]
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^([^/]+)$ /index.php?id=$1 [L]
    </IfModule>
    

    由于我更改了正则表达式(更改为([^/]+),这意味着任何不是/),它可以捕获您想要的数据,并且在这种情况下顺序无关紧要,因为它会特别匹配:

    domain.com/anything
    

    还有

    domain.com/anything/anything
    

    要修复 CSS 和图像,您可以使用 base TAG 将绝对 URL 定义到 HTML 中:

    <base href="http://domain.com/">
    

    【讨论】:

    • 更一般地说(这里不具体),您将如何添加后备?即if none of the listed conditions are satisfied, then go to url /
    • @Basj 查看更新... 最后一条规则将捕获任何未定义到其他任何地方的内容并将其发送到/
    • 感谢@Prix!是否有可能在这种情况下(后备),浏览器中显示的 URL 不是 example.com/myuncaughtURL 也不是 example.com/index.php 而只是 example.com/
    • @Basj 是的,请参阅更新。最后一条规则意味着,如果 URL 不是 domain.com/myuncaughturldomain.com/index.php,则转到 domain.com/尽管您可能希望将最后一条规则放在顶部,具体取决于您实际尝试在那里执行的操作。
    • 哦,也许我解释错了@Prix:我想要的与myuncaughturlindex.php 无关,这些只是示例(对不起,我解释错了).. . 基本上我只是希望如果这两个条件不满足,那么 1) 加载页面/index.php 2) 显示example.com/ 作为浏览器 URL...你能更新一下吗?抱歉我不是很清楚
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2016-11-18
    • 1970-01-01
    • 2012-06-09
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多