apache htaccess with if HTTP_HOST does not work with Reqrite Rule

zujrkrfu  于 12个月前  发布在  Apache
关注(0)|答案(2)|浏览(89)

我的Apache服务器上有以下.htaccess文件,该文件不起作用

<If "%{HTTP_HOST} == 'www.example.com'">
    RewriteCond %{REMOTE_ADDR} !^192\.168\.8\.8$
    RewriteRule .* - [F]

    RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [NC,L]

</If>

代码在没有if-Statement的情况下工作正常。但是使用if语句

RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [NC,L]

不起作用返回“404 Not Found”错误

js5cn81o

js5cn81o1#

<If "%{HTTP_HOST} == 'www.example.com'">
    RewriteCond %{REMOTE_ADDR} !^192\.168\.8\.8$
    RewriteRule .* - [F]

    RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [NC,L]

</If>

这个"问题"是因为mod_rewrite指令嵌入在<If>表达式中。<If>块在请求Map回文件系统之后很晚才合并。在这个上下文中,RewriteRule * pattern * 匹配的是绝对文件系统路径,而不是相对URL路径,所以上面的第二条规则不会像预期的那样匹配。
因此,规则需要这样重写:

RewriteRule ^/abs/file/path/to/docroot/([A-Za-z0-9_-]+)$ index.php?p=$1 [L]

或者,更简单地说,删除字符串开头的锚-尽管这确实会使匹配有点模糊:

RewriteRule /([A-Za-z0-9_-]+)$ index.php?p=$1 [L]

或者,最好完全避免使用<If>结构,因为您可能会与其他指令(<If>结构之外)发生意外冲突。举例来说:

RewriteCond %{HTTP_HOST} =www.example.com
RewriteCond %{REMOTE_ADDR} !^192\.168\.8\.8$
RewriteRule ^ - [F]

RewriteCond %{HTTP_HOST} =www.example.com
RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [L]

(The NC标志在第二条规则中是不必要的,因为你已经在正则表达式中匹配了A-Za-z。另外,在第一条规则中使用^而不是.*,因为您不需要在这里实际匹配任何东西。
如果你有 * 许多 * 这样的规则只适用于这一个主机,那么你可以颠倒逻辑,跳过 * N * 规则,当请求的主机是 * 不是 * 什么是预期的。举例来说:

# Skip the next 2 rules if the requested host is not "www.example.com"
RewriteCond %{HTTP_HOST} !=www.example.com
RewriteRule ^ - [S=2]

RewriteCond %{REMOTE_ADDR} !^192\.168\.8\.8$
RewriteRule ^ - [F]

RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [L]
rks48beu

rks48beu2#

我自己提出了以下的解决办法。我很喜欢。

### Access control
###
###
# Set the environment variable if the HTTP_HOST matches 'www.somehost.com'.
SetEnvIf Host "www\.somehost\.com" IS_HOST=true

# Use the set environment variable in a conditional
RewriteCond %{ENV:IS_HOST} true
RewriteCond %{REMOTE_ADDR} !^192\.168\.8\.8$
RewriteRule .* - [F]


### Rewrite Urls
###
###
RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [NC,L]

相关问题