nginx通过http_x_forwarded_for限制来访IP示例

由于入访经过负载均衡设备,后端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;}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值