Apache 使用if的特定于主机的.htaccess

Apache 使用if的特定于主机的.htaccess,apache,.htaccess,mod-rewrite,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'"> [detail

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

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

<if "%{HTTP_HOST} == 'development.project.example.org'">
    [detailed configuration...]
</if>
在.htaccess中是否可以将
重写规则
if
一起使用?我想可能是因为

“只有支持目录上下文的指令才能在中使用 此配置部分。“


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

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


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

我认为重写规则不能在
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
语句形成了一个逻辑
语句,为您提供了与封装在
if
指令中相同的逻辑来回答我自己的问题:对于同一.htaccess文件中的特定于主机的规则,我这样做了,它使用了类似于的逻辑

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


多行
SetEnvIfNoCase
是可能的。

Mod_rewrite确实支持目录上下文,因此它通过了该标准,尽管我不是说它一定会工作。当你说它不起作用时,以什么方式?当你尝试它时会发生什么?什么都不会发生-如果<代码>中的重写规则被忽略。你应该连接“如果”语句或声明,如果这两个语句都检查,也不要在mod_rewrite中混合使用P和R标志,因为它们用于不同的事情,是否要重定向或重新设置代理?与其标记我的评论以进行删除,至少尝试修复答案中的R、P标记,stackoverflow不允许,因为它只有2个字符。
<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>
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]
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