【问题标题】:host-specific .htaccess using if使用 if 的特定于主机的 .htaccess
【发布时间】:2017-02-02 16:03:38
【问题描述】:

在通过不同子域/域提供的服务上,我希望能够只使用一个 .htaccess 文件。对于%{HTTP_HOST} 的每个可能值,我都设置了if 块,如下所示:

<if "%{HTTP_HOST} == 'staging.project.example.org'">
    [detailed configuration...]
</if>

<if "%{HTTP_HOST} == 'development.project.example.org'">
    [detailed configuration...]
</if>

这适用于以下访问配置行:

<if "%{HTTP_HOST} == 'staging.project.example.org'">
    AuthType Basic
    AuthUserFile ".htusers"
    Require user example
    Order deny,allow
    Deny from all
   Allow from xxx.xx.xx.xxx
</if>

但是 RewriteRule 这样的行会被 Apache 忽略:

<if "%{HTTP_HOST} == 'production.project.example.org'">
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} !^/maintenance\.html$
    RewriteRule ^(.*)$ https://www.project.example/maintenance.html [R=307,P]
</if>

是否可以在.htaccess 中使用RewriteRuleif?我想可能是因为

"只有支持目录上下文的指令才能在内部使用 此配置部分。”
https://httpd.apache.org/docs/2.4/en/mod/core.html#if

但是有没有办法解决这个问题?

【问题讨论】:

  • Mod_rewrite 确实支持目录上下文,因此它通过了该标准,尽管我并不是说它一定可以工作。当你说它不起作用时,以什么方式?尝试后会发生什么?
  • 什么也没发生 - if 中的 RewriteRules 被忽略。
  • 你应该只连接“If”语句或声明,如果检查这两个东西,也不要在 mod_rewrite 中混合 P 和 R 标志,因为它们用于不同的东西,你想重定向还是 rev 代​​理?

标签: apache .htaccess mod-rewrite


【解决方案1】:

我认为重写规则不能在 if 指令中起作用,但您可以在重写规则本身中包含相同的逻辑:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} production.project.example.org
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ https://www.project.example/maintenance.html [R=307,P]

RewriteCond 语句形成一个逻辑 AND,为您提供与封装在 if 指令中相同的逻辑

【讨论】:

  • 与其将我的评论标记为删除,至少尝试修复答案中的 R、P 标志,stackoverflow 不允许我这样做,因为它只有 2 个字符。
【解决方案2】:

在某些情况下,If 和 mod_rewrite 可以扮演完全相同的角色,例如,在 mod_rewrite 中,“If”类似于 RewriteCond。

所以..不要将它们混合在一起,使用一个或另一个。

【讨论】:

    【解决方案3】:

    回答我自己的问题:对于同一个 .htaccess 文件中的主机特定规则,我这样做了,它使用类似于 this other answer 的逻辑。

    SetEnvIfNoCase Host staging.project.example.org $ require_auth=true
    AuthType Basic
    AuthUserFile "/path/to/your/.htusers"
    Order Deny,Allow
    Deny from env=require_auth
    Allow from xxx.xx.xx.xx # to allow certain IPs without login
    Require user ... # users from the .htusers file above that are allowed to login
    Satisfy any
    

    使用此设置,任何使用主机 staging.project.example.org 的访问都需要通过身份验证或匹配列入白名单的 IP。

    SetEnvIfNoCase 可以多行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2022-07-03
      相关资源
      最近更新 更多