两个代码教你在nginx反向代理配置中如何去除前缀

使用nginx做反向代理的时候,可以简单的直接把请求原封不动的转发给下一个服务。设置proxy_pass请求只会替换域名,如果要根据不同的url后缀来访问不同的服务,则需要通过如下方法:

方法一:加"/"

<code>server {
\tlisten 8000;
\tserver_name abc.com;
\taccess_log "pipe:rollback /data/log/nginx/access.log interval=1d baknum=7 maxsize=1G" main;

\tlocation ^ ~ / user / {
\t\tproxy_set_header Host\t$host;
\t\tproxy_set_header\tX - Real - IP $remote_addr;
\t\tproxy_set_header\tX - Forwarded - For $proxy_add_x_forwarded_for;
\t\tproxy_set_header\tX - NginX - Proxy true;

\t\tproxy_pass http : /* user/; */
\t}

\tlocation ^ ~ / order / {
\t\tproxy_set_header Host\t$host;
\t\tproxy_set_header\tX - Real - IP $remote_addr;
\t\tproxy_set_header\tX - Forwarded - For $proxy_add_x_forwarded_for;
\t\tproxy_set_header\tX - NginX - Proxy true;

\t\tproxy_pass http : /* order/; */
\t}
}
/<code>

^~/user/表示匹配前缀是user的请求,proxy_pass的结尾有/, 则会把/user/*后面的路径直接拼接到后面,即移除user。


两个代码教你在nginx反向代理配置中如何去除前缀

方法二:rewrite

<code>upstream user {
\tserver localhost : 8089 weight = 5;
}
upstream order {
\tserver localhost : 8090 weight = 5;
}

server {
\tlisten 80;
\tserver_name abc.com;
\taccess_log "pipe:rollback /data/log/nginx/access.log interval=1d baknum=7 maxsize=1G" main;

\tlocation ^ ~ / user / {
\t\tproxy_set_header Host\t$host;
\t\tproxy_set_header\tX - Real - IP $remote_addr;
\t\tproxy_set_header\tX - Forwarded - For $proxy_add_x_forwarded_for;
\t\tproxy_set_header\tX - NginX - Proxy true;

\t\trewrite ^ / user / (.*)$ / $1 break;
\t\tproxy_pass http : /* user; */
\t}

\tlocation ^ ~ / order / {
\t\tproxy_set_header Host\t$host;
\t\tproxy_set_header\tX - Real - IP $remote_addr;
\t\tproxy_set_header\tX - Forwarded - For $proxy_add_x_forwarded_for;
\t\tproxy_set_header\tX - NginX - Proxy true;

\t\trewrite ^ / order / (.*)$ / $1 break;
\t\tproxy_pass http : /* order; */
\t}
}
/<code>

proxy_pass结尾没有/, rewrite重写了url。

读者福利:下方为大家整理了BATJ最新多类面试题【多线程 高并发】,以及面试知识视频 同时还整理了一些学习资料。有需要的小伙伴可 关注+私信【资料】即可免费获取。

两个代码教你在nginx反向代理配置中如何去除前缀

两个代码教你在nginx反向代理配置中如何去除前缀

两个代码教你在nginx反向代理配置中如何去除前缀


分享到:


相關文章: