【问题标题】:Using backreference after RewriteCond in htaccess在 htaccess 中 RewriteCond 之后使用反向引用
【发布时间】:2023-03-15 12:04:01
【问题描述】:

我有:

RewriteCond %{HTTP_HOST} ^my.domain.com$ [NC]
RewriteRule ^(.*)$ index.php?q=search&keyword=$1

输入:

my.domain.com/foo_bar

我想要:

index.php?q=search&keyword=foo_bar

但事实上:

index.php?q=search&keyword=index.php

我不明白为什么。请帮帮我!

【问题讨论】:

    标签: .htaccess mod-rewrite backreference


    【解决方案1】:

    您的重写规则实际上是重写两次,一次用于/foo_bar,第二次用于index.php,因为.* 匹配任何内容。

    你只需要添加2个条件来停止对文件和目录的重写:

    # handle landing page
    RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
    RewriteRule ^/?$ index.php?q=search [L,QSA]
    
    # handle /foo_bar
    RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)$ index.php?q=search&keyword=$1 [L,QSA]
    

    【讨论】:

    • 成功了。但它也改变了我的 url 路径。我有“domain.com”和子域“my.domain.com”一起指向 1 个目录。 htaccess 文件位于根目录中。我想编写上面的代码来检测 url 何时为 my.domain.com。但我也想将子域保留在 url 中。您的代码将 url 更改为:domain.com/search/foo_bar。我期望: my.domain.com/foo_bar 代替。谢谢!
    • 不,这条规则不会改变 URL(它只是内部重写)。您有旧的浏览器缓存或其他一些规则。确保在清除浏览器缓存后进行测试,并在 .htaccess 中仅使用此规则进行测试
    • 你能教我更多吗?如果我想要 2 个重写器,例如:“my.domain.com => index.php?q=search”和“my.domain.com/foo_bar => index.php?q=search&keyword=foo_bar”那么我必须复制重写条件?我听说一个 RewriteCond 只对它之后的一个 RewriteRule 有效。
    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 2014-06-22
    • 2010-12-04
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多