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/似乎工作正常并且为前端提供服务,但是到 的请求从后端返回 404 错误/api/auth

当我查看接收后端的请求 URL 时,它总是/不正确。

我做错了什么?

编辑:我通过以下更改使其工作:

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

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

相关内容