当前位置: 首页 > Linux

Nginxproxy_set_header设置

时间:2023-04-06 02:47:46 Linux

nginx代理服务器常用配置项{listen80;服务器名称本地主机;位置/test119{proxy_set_header主机$host;proxy_set_headerX-Real-IP$remote_addr;proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;proxy_passhttp://192.168.4.120:80;}通过下面的案例了解proxy_set_header的设置其中backend192.168.4.122是提前安装的nginx第三方模块支持""echo"=============192.168.4.119proxy1nginx.confserver{listen80;server_namelocalhost;location/test119{proxy_set_headerX-Real-IP$remote_addr;proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;proxy_passhttp://192.168.4.120:80;}=============192.168.4.120proxy2nginx.confserver{listen80;server_namelocalhost;location/test{proxy_passhttp://192.168.4.121:80;}==============192.168。4.121proxy3nginx.confserver{听80;服务器名称本地主机;位置/测试{proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;proxy_passhttp://192.168.4.122:80;}==============192.168.4.122后端nginx.confserver{listen80;服务器名称本地主机;位置/测试{default_type文本/html;字符集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。192.168.4.119proxy_set_header主机$host;因为本例不涉及域名,所以没有使用$Host值,功能也比较容易理解。即当nginx作为代理时,原http请求的Header中的Host字段也被转发到请求中,如果不加这一行,nginx转发的请求头中将没有Host字段,并且服务器通过这个Host值来区分你请求的是哪个域名资源,proxy_set_headerX-Real-IP$remote_addr;只能获取上层请求ip直连服务器本身写入http请求头中的proxy_set_headerX-Real-IP$proxy_add_x_forwarded_for;定义了客户端IP,如果多层代理配置了这个值,离后端最近的会覆盖之前的值,所以一般只在连接客户端的代理上写加这个值,这样后端就可以拿到客户端的真实IP,并使用无效的proxy_set_headerX-Forwarded-For$http_x_forwarded_for;将客户端IP写入http请求头,前提是在客户端IP之前定义了X-Real-IP$remote_addr,所以使用invalidproxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;相当于$http_x_forwarded_for和$remote_addr结合起来获取上层IP,将客户端IP写入请求头,