.htaccess基本授权结合IP限制


.htaccess basic auth combined with ip restriction

我想阻止路径从我的网站使用。htaccess配置。这个想法是,只有一组特定的IP在使用基本身份验证后才能从URL访问该特定路径。

注意:这是一个路径,而不是页面或目录。我们正试图屏蔽一个web服务,所以只有post调用的URL。

我希望url example.com/rest被阻止,并且该url背后的一切都基于IP。因此应阻断example.com/rest/fooexample.com/rest/foo/bar

应用程序中的所有其他路径都应该保持功能,并且没有基本授权。

IP封锁部分已经在我之前的问题中解决了。

基本配置(阻塞部分,在。htaccess中有更多,但与这个问题无关),你可以在下面找到。

SetEnvIf Request_URI "/rest(/.*)?$" rest_uri
# Check on what subdomain we are.
SetEnvIf Host ^local'. None_Prod_Env
# Static
SetEnvIf AH_CLIENT_IP ^123'.123'.123'.123$ Allow_Host
# Range
SetEnvIf AH_CLIENT_IP ^123'.123'.123'. Allow_Host
Order deny,allow
Deny from all
Allow from env=!rest_uri
Allow from env=Allow_Host
Allow from env=None_Prod_Env

所以上面的配置阻止了对/rest/*的所有访问,但不包括对非rest路径的访问,它允许来自IP X的用户(Allow_Host变量),我们不允许生产环境,在这种情况下是本地的。

我尝试用基本的授权来扩展这个功能,像这样:

SetEnvIf Request_URI "/rest(/.*)?$" rest_uri
SetEnvIfNoCase Request_URI "/rest(/.*)?$" require_auth=true
# ... Allow Host stuff and none prod stuff ...
Order deny,allow
Deny from all
Allow from env=!rest_uri
Allow from env=Allow_Host
Allow from env=None_Prod_Env
AuthName "Password Protected"
AuthType Basic
AuthBasicProvider file
AuthUserFile /var/www/html/.htpasswd
Require valid-user

然而,这导致所有页面上的基本验证,而不仅仅是/rest/* url。我玩了很多次,但还是搞不懂。将SetEnvIfNoCase改为SetEnvIf也没有帮助。

注意:我们的服务器运行apache 2.2.22.

您可以使用几个Apache指令的组合来解决这个复杂的问题,即mod_dir, mod_setenvmod_auth_basic:

SetEnvIf Request_URI ^/rest(/.*)?$ rest_uri
# Check on what subdomain we are.
SetEnvIf Host ^local None_Prod_Env
# Static
SetEnvIf AH_CLIENT_IP ^123'.123'.123'.123$ Allow_Host
# Range
SetEnvIf AH_CLIENT_IP ^192'.168'. Allow_Host
RewriteEngine On
# block if request is /rest/* and IP is not whitelisted and not localhost
RewriteCond %{ENV:rest_uri} =1
RewriteCond %{ENV:None_Prod_Env} !=1
RewriteCond %{ENV:Allow_Host} !=1
RewriteRule ^ - [F]
# ask auth for /rest/* && NOT localhost && whitelist IP
AuthType Basic
AuthName "Password Protected"
AuthUserFile /var/www/html/.htpasswd
Require valid-user
Order deny,allow
Deny from all
Allow from env=!rest_uri
Allow from env=!Allow_Host
Allow from env=None_Prod_Env
Satisfy any

尝试将satisfy any添加到代码中。这样试试吧。

SetEnvIf Request_URI "/rest(/.*)?$" rest_uri
SetEnvIf Referer "^http://local'.example'.com/" None_Prod_Env
AuthName "Password Protected"
AuthType Basic
AuthBasicProvider file
AuthUserFile /var/www/html/.htpasswd
Require valid-user
Order deny,allow
Deny from all
Allow from env=!rest_uri
Allow from env=Allow_Host
Allow from env=None_Prod_Env
Satisfy any