1. 程式人生 > >Nginx代理proxy pass配置去除字首

Nginx代理proxy pass配置去除字首

使用Nginx做代理的時候,可以簡單的直接把請求原封不動的轉發給下一個服務。

比如,訪問abc.com/appv2/a/b.html, 要求轉發到localhost:8088/appv2/a/b.html

簡單配置如下:

upstream one {
  server localhost:8088 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 / {
        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://one;
    }

}

即,設定proxy_pass即可。請求只會替換域名。

但很多時候,我們需要根據url的字首轉發到不同的服務。

比如

abc.com/user/profile.html轉發到 使用者服務localhost:8089/profile.html

abc.com/order/details.html轉發到 訂單服務 localhost:8090/details.html

即,url的字首對下游的服務是不需要的,除非下游服務新增context-path, 但很多時候我們並不喜歡加這個。如果Nginx轉發的時候,把這個字首去掉就好了。

一個種方案是proxy_pass後面加根路徑/.

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;

        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/;
    }

}

^~/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;
    }

}

注意到proxy_pass結尾沒有/rewrite重寫了url。

關於rewrite

syntax: rewrite regex replacement [flag]
Default: —
Context: server, location, if