如何将多个 nginx proxy_pass 位置合并为一个?

How to combine multiple nginx proxy_pass locations into one?

我的 nginx 设置运行良好,我只是想看看我是否可以通过将所有这些位置与 proxy_pass 指令合并为一个来清理它:

server {
    listen       80;
    server_name  localhost;
    root   /usr/share/nginx/html;

    location /api {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    location /forgotPassword {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    location /updatePassword {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    location /register {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    location /login {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    location /logout {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    location ~ ^.+\..+$ {
        try_files $uri =404; 
    }

    location / {
        try_files $uri /index.html;
    }

    error_page  404              /404.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

正如你所看到的,它们每个的内容是相同的,唯一的区别是前缀。

是否有一种逻辑上等效的方法可以在不改变行为的情况下干掉它?

沿着这些尝试一些东西..

server {

    <..>

    location ~ ^/(api|forgotPassword|updatePassword|register|login|logout) {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend:1337;
    }

    <..>

}