nginx代理常用配置项

 server {
        listen       80;
        server_name  localhost;
        location /test119 {
                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://192.168.4.120:80;
        }

通过以下的案例来理解proxy_set_header设置

其中backend 192.168.4.122 提前安装nginx 第三方模块支持 ""echo"

=============192.168.4.119 proxy1 nginx.conf

 server {
        listen       80;
        server_name  localhost;
        location /test119 {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://192.168.4.120:80;
        }

=============192.168.4.120 proxy2 nginx.conf

server {
        listen       80;
        server_name  localhost;
        location /test {
                proxy_pass http://192.168.4.121:80;
        }

=============192.168.4.121 proxy3 nginx.conf

server {
        listen       80;
        server_name  localhost;
        location /test {
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_pass http://192.168.4.122:80;
        }

=============192.168.4.122 backend nginx.conf

server {
        listen       80;
        server_name  localhost;
        location /test {
             default_type text/html;
             charset gbk;
             echo "$remote_addr ||$http_x_real_ip  ||$http_x_forwarded_for"
        }
在192.168.44.254 上访问 [http://192.168.4.119/test119](http://192.168.4.119/test119)

192.168.4.121 ||192.168.4.254 ||192.168.4.254, 192.168.4.120

有注意到 ||192.168.4.254, 192.168.4.120 是不包含192.168.4.119

proxy_set_header Host $host;
本案例因为不涉及到域名所以用不到$Host值,作用也比较好理解,就是nginx做代理时,把原http请求的Header中的Host字段也放到转发的请求里,如果不加这一行的话,nginx转发的请求header里就不会有Host字段,而服务器是靠这个Host值来区分你的请求的是哪个域名的资源的,

proxy_set_header X-Real-IP $remote_addr;
只能获取到与服务器本身直连的上层请求ip 写入到http请求头中

proxy_set_header X-Real-IP $proxy_add_x_forwarded_for;
定义客户端IP,如果多层代理都有配置这个值,离backent最近的会覆盖之前的值 所以一般只在连接客户端的代理上写添加这条值,这样backend就能获取到客户端的真实IP,单独使用无效

proxy_set_header X-Forwarded-For $http_x_forwarded_for;
把客户端IP写入到http请求头中,前提是之前有X-Real-IP $remote_addr定义过客户端IP,所以单独使用无效

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
相当于 $http_x_forwarded_for 和 $remote_addr和结合 获取上层IP和把客户端IP写入请求头中,


Bigyong
28 声望13 粉丝