仅在访问特定域时才使用HTTP Auth

Dav*_*ong 10 apache authentication .htaccess

我有几个网站: example.com,example1.com,和example2.com.所有这些都指向我的服务器/public_html文件夹,这是我的Apache根文件夹.

.htaccess仅当用户来自时,我需要添加到我的文件中才能使用http身份验证example2.comexample.com并且example1.com不应该使用身份验证.

我知道我需要类似的东西

AuthType Basic
AuthName "Password Required"
AuthUserFile "/path/to/.htpasswd"
Require valid-user
Run Code Online (Sandbox Code Playgroud)

但是我只想在用户访问时要求输入密码example2.com.

编辑

使用答案中建议的方法,我在.htaccess文件中有以下内容:

SetEnvIfNoCase Host ^(.*)$ testauth
<IfDefine testauth>
RewriteRule ^(.*)$ index2.php?q=$1 [L,QSA]
</IfDefine>
Run Code Online (Sandbox Code Playgroud)

我知道mod_setenvif.c模块已启用(我使用<IfModule>块验证),但似乎"testauth"永远不会定义,因为我的测试验证(重定向到index2.php)没有执行(而它是在我的<IfModule>块中执行的.有什么想法吗?

Jon*_*Lin 19

在文档根目录中的htaccess文件中,有什么内容如下:

# set the "require_auth" var if Host ends with "example2.com"
SetEnvIfNoCase Host example2\.com$ require_auth=true

# Auth stuff
AuthUserFile /var/www/htpasswd
AuthName "Password Protected"
AuthType Basic

# Setup a deny/allow
Order Deny,Allow
# Deny from everyone
Deny from all
# except if either of these are satisfied
Satisfy any
# 1. a valid authenticated user
Require valid-user
# or 2. the "require_auth" var is NOT set
Allow from env=!require_auth
Run Code Online (Sandbox Code Playgroud)

这将使它所以不需要身份验证,除非主机结尾example2.com(例如www.example2.com,dev.example2.com等).如果需要,可以调整表达式.任何其他主机将导致require_authVAR不要让这样设置在验证必需的.如果这需要相反,最后一行可以更改为:Allow from env=require_auth,删除!.

  • 对我来说!require_auth不起作用,但这样做:允许所有拒绝来自env = require_auth要求有效用户满足任何 (3认同)

reb*_*ken 12

Apache 2.4提供了一个使用If指令的语义替代方法:

<If "req('Host') == 'example2.com'">
    AuthUserFile /path/to/htpasswd
    AuthType Basic
    AuthName "Password Protected"
    Require valid-user
</If>
<Else>
    Require all granted
</Else>
Run Code Online (Sandbox Code Playgroud)


Wil*_*nly 5

这是一个建议:

创建一个名为的文件common.conf并保存在可访问的位置

在此文件中,将Apache配置放在所有站点(主机)的公共位置.

删除当前单个VirtualHost条目以替换VirtualHost条目,如下所示:

# These are the password protected hosts
<VirtualHost *:80>
ServerName example.com
ServerAlias example1.com

Include /path-to-common-configuration/common.conf

AuthType Basic
AuthName "Password Required"
AuthUserFile "/path/to/.htpasswd"
Require valid-user
</VirtualHost>

# These are hosts not requiring authentication
<VirtualHost *:80>
ServerName example2.com
ServerAlias example3.com

Include /path-to-common-configuration/common.conf

</VirtualHost>
Run Code Online (Sandbox Code Playgroud)


Mar*_*wis 1

您不应该将每个虚拟主机的配置放入 .htaccess 中。相反,请将配置块放在/etc/apache/sites-enabled/*.