nginx正規表示式反向代理位置

nginx正規表示式反向代理位置

我嘗試創建一個基於位置的反向代理。
我的配置沒有按預期工作。

/api它應該將向後端發出的每個請求傳遞給/auth後端,並將其他所有請求傳遞給前端伺服器。

server {

 listen 80;
 server_name 127.0.0.1 localhost;

 # remove server version
 server_tokens off;

 try_files $uri $uri/ =404;

 autoindex off;

 location = /favicon.ico { access_log off; log_not_found off; }
 location = /robots.txt  { access_log off; log_not_found off; }

 location ~ ^/(api|auth)/ {
     proxy_pass http://127.0.0.1:8080/$1;
     proxy_http_version 1.1;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_set_header Connection $connection_upgrade;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }

 location ~ ^/(.*) {
     proxy_pass http://127.0.0.1:3000/$1;
     proxy_http_version 1.1;
     proxy_set_header X-Forwarded-Proto $scheme;
     proxy_set_header Connection $connection_upgrade;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }

}

對 的請求似乎運作正常並且為前端提供服務,但對後端的http://example.com/請求/api或傳回 404 錯誤。/auth

當我查看接收後端的 reuqest URL 時,它始終/是不正確的。

我做錯了什麼?

編輯:我透過以下更改使其正常工作:

    location ~ /(api|auth)/(.*)$ {
        proxy_pass http://127.0.0.1:8080/$1/$2;
        ...
    }

    location ~ /(.*)$ {
        proxy_pass http://127.0.0.1:3000/$1;
        ...
    }

相關內容