最近在用nginx做反向代理,随后发现一个严重问题,就是反向代理的站点存在一个url,返回一个响应将请求301重定向到某个链接中。
为了解决这个问题,我们通过使用nginx的more_set_headers
模块来解决。
nginx不内置more_set_headers模块,我们需要自行下载模块与编译nginx。
下载nginx
在编译nginx的./configure ...
命令后追加--add-module=模块链接
来准备将模块编译进nginx
使用make
和make install
。
在你指定的位置寻找nginx的配置。
这里我编译时的参数为
此配置可能会出现配置残缺功能补全等状况,仅供参考
来源nginx入门之—-编译安装 - 知乎 (zhihu.com)
1 | ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-pcre --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_image_filter_module --with-http_slice_module --with-mail --with-threads --with-file-aio --with-stream --with-mail_ssl_module --with-stream_ssl_module --add-module=../headers-more-nginx-module/ |
注意,我所放置的nginx源码目录和模块目录处于相同目录下,所以在添加模块时我使用相对路径../headers-more-nginx-module/
来指定模块源码根目录。
由于我没有指定配置文件的路径--conf-path
,所以在使用make install 后应到安装路径--prefix
中修改配置文件。
查看文档
https://github.com/openresty/headers-more-nginx-module#synopsis
可知使用more_set_headers -s [code] '[key]: [value]'
来指定当状态码为[code]
时添加或修改响应头[key]: [value]
。
在我的配置文件/usr/local/nginx/conf/nginx.conf
中修改
1 | server { |
其中,我们可以发现两个参数$uri
和$args
,这两个参数为nginx的内置变量,$uri
为从域名往后直到最后的路径,而$args
为请求携带的参数。在这里我正好需要这两个参数来实现重定向。
在配置完成nginx后,保存配置,重启nginx。