Nginx设置反向代理非常简单,只需要在想要做代理服务器的Nginx conf配置文件中,Server块下面添加proxy_pass即可。
例如:
server {
server_name example.com;
location / {
proxy_pass https://destinationsite.com;
}
}
这样就设置好了example.com反向代理destinationsite.com,也就是说用户访问example.com时,实际是访问了destinationsite.com,并且地址栏显示的仍然是example.com,因为是通过example.com所在服务器代理了destinationsite.com网站,通过代理服务器来访问并返回目标网站的内容给到用户。
如果目标网站访问速度较慢等场景下,就可以通过一个中转服务器来代理,实现更方便地访问了。
但是,只是这样设置的话,你会发现目标网站上的其他链接仍然是原域名的,也就是说如果用户点击的话,仍然会直连目标服务器。要解决这个问题,我们需要在location模块中添加如下内容:
sub_filter 'destinationsite.com' 'example.com';
sub_filter_once off;
使用sub_filter将destinationsite.com域名全都替换为代理服务器的域名,这样用户点击目标网站上的链接时,就都是通过代理域名来访问啦。sub_filter还可以用来替换其他内容,详情参考:http://nginx.org/en/docs/http/ngx_http_sub_module.html
完整配置:
server {
server_name example.com;
location / {
proxy_pass https://destinationsite.com;
sub_filter 'destinationsite.com' 'example.com';
sub_filter_once off;
}
}
如果目标服务器启用了压缩,则会导致sub_filter语句失效,因为接收到的数据是经过压缩的,Nginx无法进行替换。此时,可以在proxy_pass语句后添加:proxy_set_header Accept-Encoding “”; 告诉目标服务器不要压缩,一般能够生效,但是部分目标服务器可能是用了强制压缩,此时就需要使用其他方案。
通过搜索,发现有网友分享了两种解决方案:
一种是对接收到的内容实用gunzip模块进行解压缩,就能正常替换。需要配置gunzip模块重新编译nginx,以及添加gzip_disable “.”;,详情可以搜索解决方案;
另一种是进行两次反向代理,第一次反代时不进行替换,并且关掉压缩,第二次反代时进行替换。
注意:支持sub_filter需要Nginx 带有ngx_http_sub_module模块,如果没有带的话,就需要配置该模块重新编译安装Nginx了。