.htaccess 虚拟主机的基本身份验证?
我想知道是否可以根据 .htaccess 文件中的虚拟主机 URL 设置条件 http 基本身份验证要求。
例如,我想要做的是让 mysite.com 和 test.mysite.com 在同一目录中运行相同的代码库,但使用密码保护 test.mysite.com。它将以这种方式设置,这样我就不需要分支我的代码,因为我的应用程序代码可以看到它正在从哪个虚拟主机/url 提供服务,并选择从中提供内容的数据库。
I was wondering if it was possible to setup a conditional http basic auth requirement based on the virtual host URL in an .htaccess file.
For example what I want to do is have mysite.com and test.mysite.com run off the same code base in the same directory but password protect test.mysite.com. It would be setup this way so that I wouldn't need to branch my code since my app code can see which vhost/url it's being served from and pick the database to serve content from.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过使用
mod_setenvif
和mod_auth
模块来解决这个问题。使用SetEnvIfNoCase
指令设置受密码保护的主机。您需要一些额外的指令来满足访问:然后在
Directory
块内(或公开)您有您的身份验证内容设置,如下所示:现在是 require/satisfy stuff:
这将使任何与
^test\.mysite\.com\.?(:80)?$
不匹配的主机无需身份验证即可访问(Allow从env=!PROTECTED_HOST
),但除此之外,我们需要一个有效的用户(需要有效用户
)。满足任何
确保我们只需要两者之一,即“允许”或“要求”。You can sort of kludge this by using
mod_setenvif
along with themod_auth
modules. Use theSetEnvIfNoCase
directive to set which host is password protected. You'll need a couple of extra directives to satisfy access:Then inside the
Directory
block (or just out in the open) you have your auth stuff setup, something like this:Now for the require/satisfy stuff:
This will make it so any host that doesn't match
^test\.mysite\.com\.?(:80)?$
will have access without need for auth (Allow from env=!PROTECTED_HOST
) but otherwise, we need a valid user (Require valid-user
). TheSatisfy any
ensures that we just need one of the 2, either the Allow or Require.我在实施乔恩的解决方案时遇到了问题:
尽管我对 Apache conf 和正则表达式非常熟悉,但身份验证总是被触发。从快速分析来看,
Allow from env=!PROTECTED_HOST
行似乎没有启动。但我发现了另一个对我来说实际上看起来更安全的解决方案:
我为指向的两个域创建了两个虚拟主机相同的文档根(顺便说一下,这是完全允许的)。在其中一个虚拟主机中,我添加了基本身份验证指令(直接进入虚拟主机指令块)。
就像魅力一样。而且我有更好的感觉,这确实很安全 - 没有风险忽略正则表达式模式中的任何细节,这些细节会为入侵者打开大门。
I had problems implementing Jon's solution:
Although I am quite familiar with Apache conf and regular expressions, the authentication always fired. From a quick analyzes it looked like the
Allow from env=!PROTECTED_HOST
line did not kick in.But I found another solution that actually looks safer to me:
I created two virtual hosts for the two domains pointing to the same document root (which is fully allowed by the way). In one of the vhosts I added the directives for basic auth (directly into the vhost directive block).
Works like a charm. And I have a better feeling that this is really safe - no risk to overlook any details in the regex pattern that would open up the gates for intruders.
这是一个类似于 Jon Lin 提出的解决方案,但使用
RewriteCond
来检查主机名:Here's a solution similar to what Jon Lin proposed, but using
RewriteCond
to check the host name: