nginx反向代理入门(2) :proxy_set_header、代理多个网站

https://blog.csdn.net/github_26672553/article/details/81902645
前面已经学习了使用proxy_pass指令来实现反向代理,但是并不完善,网站如何获取主机?

$_SERVER['HTTP_HOST']; 这是php获取请求头中的Host函数,由于我们做了反向代理,最终发现该值是服务端的真实IP,而不是域名。
比如http://abc.com 我们希望得到的值是 abc.com

##使用proxy_set_header指令
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header

为了解决这些问题,我们需要学习proxy_set_header指令,重新定义或添加字段传递代理服务器的请求头。


server{
listen 8082;
location /{
proxy_set_header Host a123; #这时我们获取的HTTP_HOST就变成了我们自定义的a123
proxy_pass http://192.168.88.88:9090/;
}
}

一般来说我们会使用nginx内置变量$host来自动获取,当请求端头部有Host值取该值,否则取主域名。

proxy_set_header Host $host;

把端口加上(非必需)

proxy_set_header Host $host:$server_port;

代理多网站

当我们访问
http://abc.com:8082/php 时进入php网站;
http://abc.com:8082/java 时进入java网站.

简单配置如下:

location /php{
    proxy_set_header Host $host:$server_port; 
    proxy_pass http://192.168.88.88:9090/;
}
location /java{
    proxy_set_header Host $host:$server_port; 
    proxy_pass http://192.168.88.88:8080/;
}

猜你喜欢

转载自blog.csdn.net/github_26672553/article/details/81904114