特定于主机的.htaccess使用if

时间:2017-02-02 16:03:39

标签: apache .htaccess mod-rewrite

在通过不同子域/域提供的服务上,我希望只能使用一个.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

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

3 个答案:

答案 0 :(得分: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指令中的逻辑相同的逻辑

答案 1 :(得分:0)

如果和mod_rewrite在某些情况下可以扮演完全相同的角色,例如,在mod_rewrite中&#34; If&#34;就像RewriteCond。

所以..不要将它们混合在一起,使用其中一种,或者另一种。

答案 2 :(得分:0)

要回答我自己的问题:对于同一个.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是可能的。