情景: 公司最近将一个服务通过nginx反向代理的方式映射到了外网上,又想要限制允许某些固定ip访问
实现:
1.如果想要对所有网站生效,那么需要在Nginx的配置文件夹里创建一个名为“license.conf”的配置文件:
allow 10.10.10.10;#ip
allow 20.20.20.20;
allow 10.10.10.0/24;#ip段
deny all;
2.但是公司的Nginx代理了很多网站,而且只想让针对当前网站单独设置限制某些固定ip访问,这种情况只能修改对应的conf文件:
server {
listen 80;
server_name xxxx.xxxx.com.cn;
location / {
proxy_pass http://192.168.1.1;
allow 10.10.10.10; #客户ip1
allow 20.20.20.20; #客户ip2
deny all;
#proxy_redirect ~^(http://[^:]+):\d+(/.+)$ $1$2;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 100m;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffering off;
proxy_request_buffering off;
}
}
3.后来发现,流到nginx的数据流是经过负载均衡、防火墙等其他网络设备,访问的ip并不是客户的ip,而2中的方法只能对流到nginx的数据来源做IP控制。所以选择通过http_x_forwarded_for实现访问控制:
map $http_x_forwarded_for $accessip {
default false;
#10.10.10.10(IP匹配)
10.10.10.10 true;
20.20.20.20 true;
#10.10.50.0/24(网段匹配)
10.10.10.0/24 true;
}
server {
listen 80;
server_name xxxx.xxxx.com.cn;
if ( $accessip = 'false') {return 405;}
location / {
proxy_pass http://192.168.1.1;
#proxy_redirect ~^(http://[^:]+):\d+(/.+)$ $1$2;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 100m;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffering off;
proxy_request_buffering off;
}
}
这样只有允许的ip才能被转发,否则会被返回错误值405(这个值可以自己定义)