nginx_host作用
nginx_host作用
nginx在做代理时,设置请求头的Host的作用是啥?进行探究。
重要:nginx作为反向代理时,比如转发给apache,如果没有指定Host的请求头,后端的apache工作可能不正常。具体表现在:登录时,在跳转时,可能因为缺少端口,而跳转后没有端口信息了。所以,需要添加Host请求头信息。 后端的apache在层层代理下,可能不清楚最外层的端口。
另外,在单点登录时,有个应用也是未正确设置Host时,导致登录成功后,跳转地址不正确。
在如下的情景中,代码部署在docker环境中,而docker中nginx(80端口)代理了内部的apache(81端口),请求的时候,是从用nodeIP:nodePort的形式进行访问,内部nginx是无法感应到外部nodePort的访问端口,
在跳转的时候,自动回到nodeIP:80进行访问。
因此,需要一种机制,强制的将端口传入到内部。
在nginx中增加了proxy_set_header Host 参数,host是请求头中的信息,在转发给81端口apache之前,强制的覆盖掉host信息。包括单点登录的时候。APP_PORT为端口
nginx配置
location ~ \.php$ {
proxy_set_header Host $host:APP_PORT;
#proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:81;
}
Dockerfile配置,增加run.sh
ADD run.sh /
RUN chmod +x /run.sh
CMD ["/run.sh"]
run.sh中,增加逻辑,从环境变量中获取,动态的修改APP_PORT
#!/bin/sh
#动态的修改端口,如果没有,则删除APP_PORT该行。
if [ $APP_PORT ];then
sed -i "s/APP_PORT/$APP_PORT/g" /etc/nginx/nginx.conf
else
sed -i "/APP_PORT/d" /etc/nginx/nginx.conf
fi
echo "10.19.18.30 cas.yundasys.com"> /etc/hosts && nginx && ./startup.sh
启动的时候,需要从环境变量中传入APP_PORT,这个端口,即nodePort。