由于入访经过负载均衡设备,后端nginx无法获取client_ip,只能通过http_x_forwarded_for获取到最原始用户IP。这里通过http_x_forwarded_for来限制固定IP的用户可以访问。

普通client_ip限制方法

#反向代理地址
upstream sandbox-open {
    server 10.10.10.5:8080;
}

#30001对外端口
server {
    listen 30001;
    server_name  sandbox.open.com;

    access_log  /var/log/nginx/sandbox-open_access.log;
    client_max_body_size   20m;

    location / {

	# 仅允许如下client_ip访问
	allow 10.10.10.12;
	allow 10.10.11.12/24;
	deny all;

      proxy_http_version 1.1;
      proxy_set_header Connection ""; 
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass  http://sandbox-open;
      proxy_redirect off;
   }

http_x_forwarded_for限制方法1(推荐)

#http_x_forwarded_for地址不在下列IP中则返回403
map $http_x_forwarded_for $accessip {
	default false;
	#10.10.10.10(IP匹配)
	10.10.10.10 true;
	10.10.10.11 true; 
	10.10.10.12 true;  
	#10.10.50.0/24(网段匹配)
	~*10.10.50. true;
}

#反向代理地址
upstream sandbox-open {
	server 10.10.10.5:8080;
}

#30001对外端口
server {
    listen 30001;
    server_name  sandbox.open.com;

    access_log  /var/log/nginx/sandbox-open_access.log;
    client_max_body_size   20m;

    location / {
		#http_x_forwarded_for地址不在下列IP中则返回403
		if ( $accessip = 'false') {return 403;}

		proxy_http_version 1.1;
		proxy_set_header Connection ""; 
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass  http://sandbox-open;
		proxy_redirect off;
   	}

http_x_forwarded_for限制方法2

#反向代理地址
upstream sandbox-open {
    server 10.10.10.5:8080;
}

#30001对外端口
server {
    listen 30001;
    server_name  sandbox.open.com;

    access_log  /var/log/nginx/sandbox-open_access.log;
    client_max_body_size   20m;

    location / {
		#http_x_forwarded_for地址不在下列IP中则返回403
		set $accessip false;
		if ( $http_x_forwarded_for = '10.10.10.10' )  {set $accessip true;}
		if ( $http_x_forwarded_for = '10.10.10.11' )  {set $accessip true;}
		if ( $http_x_forwarded_for = '10.10.10.12' )  {set $accessip true;}
		if ( $http_x_forwarded_for = '192.168.1.1' )  {set $accessip true;}
		if ( $accessip = 'false') {return 403;}

		proxy_http_version 1.1;
		proxy_set_header Connection ""; 
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass  http://sandbox-open;
		proxy_redirect off;
   }

此方法测试后发现只能单个IP添加 用如下正则匹配IP段匹配不到
if ( $http_x_forwarded_for = ‘~*10.10.50.’ ) {set $accessip true;}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐