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

时间:2016-01-29 02:16:42

标签: nginx reverse-proxy

我的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;
    }

}

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

在不改变行为的情况下,是否存在逻辑等效的方法来干这个?

1 个答案:

答案 0 :(得分:2)

尝试一下这些......

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

    <..>

}