nginx下目录限制ip访问的解决办法

2009-05-13 15:23:38来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折


[url=javascript:;]apache[/url]
下限制某个目录访问很容易的,
[url=javascript:;]nginx[/url]
下的方法也差不多,只不过大家用的少而已,我简单的总结一下:
根据nginx的文档:
QUOTE:
ngx_http_access_module
This module provides a simple host-based access control.
Module ngx_http_access_module makes it possible to control access for specific IP-addresses of clients. Rules are checked in the order of their record to the first match.
Example configuration
[url=javascript:;]location[/url]
/ {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
deny all;
}
In the above example access is only granted to networks 10.1.1.0/16 and 192.168.1.0/24 with the exception of the address 192.168.1.1.
When implementing many rules, it is generally better to use the ngx_http_geo_module.根据这个文档,比如我要限制private这个目录的访问,用如下规则
location /private{
allow 192.168.1.0/24;
deny all;
}
location ~ \.php$
{
include conf/enable_php5.conf;
}
这个时候实验会发现,private目录下的
[url=javascript:;]php[/url]
之外的
[url=javascript:;]文件[/url]
确实只有192.168.1.0这个网段的机器访问,但是php文件却依然可以访问,这是为什么哪?
因为nginx的匹配方式是
[url=javascript:;]正则表达式[/url]
优先级比较高。因此PHP解析用的是正则表达式进行匹配,而要限制的目录如果不是用正则表达式,所以,就算是要限制的目录,因为PHP还是能被匹配到,所以,还是解析PHP了。
所以,如果想解决的话,需要把目录也写成正则匹配,而且要放在PHP的前面,否则就会先匹配PHP。
location ~ ^/private/ {
allow 192.168.1.0/24;
deny all;
}
location ~ \.php$
{
include conf/enable_php5.conf;
}
改成这样以后,会发现php文件提示打开、保存,我点了保存以后,
[url=javascript:;]下载[/url]
回来的文件就是明文的
[url=javascript:;]源代码[/url]
。这又是为什么哪?
根据nginx的文档:
QUOTE:
location
syntax: location [=|~|~*|^~] /uri/ { ... }
default: no
context: server
This directive allows different configurations depending on the URI. It can be configured using both conventional strings and regular expressions. To use regular expressions, you must use the prefix ~* for case insensitive match and ~ for case sensitive match.
To determine which location directive matches a particular query, the conventional strings are checked first. Conventional strings match the beginning portion of the query and are case-sensitive - the most specific match will be used (see below on how nginx determines this). Afterwards, regular expressions are checked in the order defined in the configuration file. The first regular expression to match the query will stop the search. If no regular expression matches are found, the result from the convention string search is used.在location中使用正则表达式去匹配的话,第一个匹配上的就不会再去匹配别的规则了,因此下面的那个匹配php文件的规则实际上被忽略了,因此php文件访问的时候就提示是打开还是保存了。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:nginx location的匹配优先规则

下一篇:Removing dead mailing lists from Mailman