ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

nginx根据真实IP分发请求

2022-06-24 14:06:36  阅读:234  来源: 互联网

标签:分发 请求 nginx IP server header html proxy


nginx根据真实IP分发请求

使用场景

2022年6月份,社保局接收到上级的文件,要求建立统一的门户系统(所有的用户都通过门户系统登录到子系统,原子系统的用户、角色、机构、权限等,都交给门户网站来控制)。于是各个子系统就需要做一个适配性的改造,子系统有机关养老、企业养老、城乡居民养老、工伤保险、失业保险等。在子系统改造的过程中,除了代码层面的改造以外我们遇上了几个关于负载方面的问题。

传统运行方式

会话保持(低成本方式)解决session问题

在原来的子系统中,为了一定程度上解决服务器压力的问题,我们其实已经用nginx做了一个代理,两个负载地址作为双活部署。目前的系统有个做的不是很好的地方,就是在session里面塞了不少的东西,如果客户端的请求第一次发到了server1上,第二次发到了server2上,很有可能就因为这两个会话的不同,导致里面的参数获取不到,所以我们要考虑session共享或者会话保持的问题。其实这个问题已经解决了,项目组选择的方式是会话保持。具体的方法就是在配置nginx的时候,请求的分发策略选择ip-hash,这样一来,一个ip在两台服务器都运行正常的情况下,永远只会发到某一台上。一旦某一台服务器宕机,其实上述的问题还是会出现,但是我们就不考虑这个情况了,毕竟出现的概率比较小,这边的成本想控制到最低。

# nginx配置如下
upstream jgyl{
	zone upstreams 64K;
	ip-hash
	server 10.40.29.153:8080;
	server 10.40.29.126:8080;
}

问题复现

nginx代理失效

在参与门户系统的集成中,请求的方式发生了如下变化:

原:客户端请求 → nginx → 负载服务器

现:客户端请求 → 门户网关 → 【用户认证中心 → 门户网关】 → nginx → 负载服务器

其中访问用户认证中心主要是为了获取用户认证的标识,即token,有token的时候就不需要括号中的部分了。

在现有的请求方式下,nginx认为所有的请求都来自门户网关而不是,客户端,所以所有分发的请求都会发到一台服务器上面,于是nginx的代理在实际层面上就失效了。

解决办法

在解决这个问题的时候,我们讨论了几种解决方式。在传统方式的基础下,session利用redis来共享显然是不太好的,因为代价比较大,而且redis必须安装在一个共享的目录里面。利用数据库共享看似不错,但是网上的解决方案完全不够成熟。所以我们还是想看看有没有办法让它还原到原来的运行模式上,总之百转千回,终于找到了解决方案。那就是让nginx根据真实的IP的分发请求。

X-Forwarded-ForXFF)是用来识别通过HTTP代理或负载均衡方式连接到Web服务器的客户端最原始的IP地址的HTTP请求头字段,我们的核心思路就是在这个字段里面获取最早的一个请求,原理如下:

1、客户端请求(ip0) → 服务器(ip1)。request.getHeader("X-Forwarded-For"); // 空

2、客户端请求(ip0) → nginx(ip1)→ 服务器(ip2)。request.getHeader("X-Forwarded-For"); // ip0

3、客户端请求(ip0) → 请求转发器1(ip1) → 请求转发器2(ip2) → nginx(ip3)→ 服务器(ip4)。

request.getHeader("X-Forwarded-For"); // ip0,ip1,ip2

其中ip0是最初始的IP请求,ip-hash默认以ip2作为请求IP来分发请求。

所以我们通过这个字段来加工出ip0,之后用它来分发请求就可以了,核心的配置如下。

# nginx配置如下
map $http_x_forwarded_for  $clientRealIp {
	"" $remote_addr;
	~^(?P<firstAddr>[0-9\.]+),?.*$ $firstAddr;
}
	
upstream jgyl{
	zone upstreams 64K;
	hash  $clientRealIp;
	server 10.40.29.153:8080;
	server 10.40.29.126:8080;
}

完整的配置

这里要注意X-Forwarded-For虽然是一个可用的标准,但是并非所有途中的转发器都会增加值,需要每个转发器都设置上(以nginx举例):

proxy_set_header Host $host:$server_port; # 传 header 参数至后端服务
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 设置request header 即客户端IP地址


#user  nobody;
worker_processes  auto;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  info;

pid        logs/nginx.pid;

worker_rlimit_nofile 65535;
events {
	use	epoll;
    worker_connections	65535;
}


http {

    map $http_x_forwarded_for  $clientRealIp {
       ""      $remote_addr;
       ~^(?P<firstAddr>[0-9\.]+),?.*$  $firstAddr;
    }
	
	upstream jgyl{
		zone upstreams 64K;
		hash  $clientRealIp;
		server 10.40.29.153:8080;
		server 10.40.29.126:8080;
	}
	
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;
	
    # 客户端请求头缓冲大小
    # nginx 默认会用 client_header_buffer_size 这个 buffer 来读取 header 值
    # 如果 header 过大,它会使用 large_client_header_buffers 来读取
    # 如果设置过小的 HTTP 头,或 Cookie 过大, 会报400 错误 nginx 400 bad request
    # 如果超过 buffer,就会报 HTTP 414 错误 (URI Too Long)
    # nginx 接受最长的 HTTP 头部大小必须比其中一个 buffer 大
    # 否则就会报 400 的 HTTP 错误 (Bad Request)
    client_header_buffer_size  32k;
    large_client_header_buffers  4  32k;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  90;

    # gzip模块设置,使用 gzip 压缩可以降低网站带宽消耗,同时提升访问速度。
    # 开启gzip
    gzip  on;
    # 最小压缩大小
    gzip_min_length  1k;
    # 压缩缓冲区
    gzip_buffers  4 16k;
    # 压缩版本
    gzip_http_version  1.0;
    # 压缩等级
    gzip_comp_level  2;
    # 压缩类型
    gzip_types   text/plain text/css text/xml text/javascript application/json application/x-javascript application/xml application/xml+rss;

    server {
        listen       8001;
        server_name  17.167.18.18;
		
		fastcgi_connect_timeout 75;  #链接
        fastcgi_read_timeout 90;   #读取
        fastcgi_send_timeout 100;   #发请求
		
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
		proxy_set_header Host $host:$server_port; # 传 header 参数至后端服务
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 设置request header 即客户端IP地址
		proxy_connect_timeout 60s;
		proxy_send_timeout 1800;
		proxy_read_timeout 1800;
		client_max_body_size 100m;
		# 缓冲区代理缓冲用户端请求的最大字节数
		client_body_buffer_size  128k;
		# 设置代理服务器(nginx)保存用户头信息的缓冲区大小
		proxy_buffer_size  4k;
		# proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
		proxy_buffers  4  32k;
		# 高负荷下缓冲大小(proxy_buffers*2)
		proxy_busy_buffers_size  64k; 
		# 设定缓存文件夹大小,大于这个值,将从upstream服务器传
		proxy_temp_file_write_size  64k;
			
		location /jgyl {
			root   html;
			index  index.html index.htm;
			proxy_pass   http://jgyl/jgyl;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

标签:分发,请求,nginx,IP,server,header,html,proxy
来源: https://www.cnblogs.com/gengyp/p/15522251.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有