How to remove prefix in nginx reverse proxy configuration

王林
Release: 2023-05-11 21:07:11
forward
3849 people have browsed it

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

方法一:加"/"

server {
    listen              8000;
    server_name         abc.com;
    access_log  "pipe:rollback /data/log/nginx/access.log interval=1d baknum=7 maxsize=1g"  main;
 
    location ^~/user/ {
        proxy_set_header host $host;
        proxy_set_header  x-real-ip        $remote_addr;
        proxy_set_header  x-forwarded-for  $proxy_add_x_forwarded_for;
        proxy_set_header x-nginx-proxy true;
 
        proxy_pass http://user/;
    }
 
    location ^~/order/ {
        proxy_set_header host $host;
        proxy_set_header  x-real-ip        $remote_addr;
        proxy_set_header  x-forwarded-for  $proxy_add_x_forwarded_for;
        proxy_set_header x-nginx-proxy true;
 
        proxy_pass http://order/;
    }
}
Copy after login

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

方法二:rewrite

upstream user {
 server localhost:8089 weight=5;
}
upstream order {
 server localhost:8090 weight=5;
}
 
server {
 listen  80;
 server_name abc.com;
 access_log "pipe:rollback /data/log/nginx/access.log interval=1d baknum=7 maxsize=1g" main;
 
 location ^~/user/ {
 proxy_set_header host $host;
 proxy_set_header x-real-ip $remote_addr;
 proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
 proxy_set_header x-nginx-proxy true;
 
 rewrite ^/user/(.*)$ /$1 break;
 proxy_pass http://user;
 }
 
 location ^~/order/ {
 proxy_set_header host $host;
 proxy_set_header x-real-ip $remote_addr;
 proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
 proxy_set_header x-nginx-proxy true;
 
 rewrite ^/order/(.*)$ /$1 break;
 proxy_pass http://order;
 }
}
Copy after login

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

The above is the detailed content of How to remove prefix in nginx reverse proxy configuration. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template