首页 > 解决方案 > 在nginx中根据request_method设置proxy_pass

问题描述

我有两个应用程序和一个 nginx 服务器。我想将 nginx 上的所有 GET 请求代理到在http://127.0.0.1:9101/上运行的一个应用程序,并将所有其他请求方法代理到http://10.41.115.241:8000/

我尝试了几个选项,但没有一个有效我尝试使用 limit_exempt

  location /api/v1/executions {
    error_page 502 = @apiError;

    rewrite ^/api/(.*)  /$1 break;

    proxy_pass            http://127.0.0.1:9101/;

    limit_except PUT POST DELETE {
      proxy_pass http://10.41.115.241:8000/;
    }


    proxy_read_timeout    90;
    proxy_connect_timeout 90;
    proxy_redirect        off;

    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 Connection '';
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;
    #proxy_set_header Host $host;
  }

我也试过如果条件

  location /api/v1/executions {
    error_page 502 = @apiError;

    rewrite ^/api/(.*)  /$1 break;


    proxy_pass http://10.41.115.241:8000/;

    if ($request_method = GET) {
      proxy_pass            http://127.0.0.1:9101/;
    }

    proxy_read_timeout    90;
    proxy_connect_timeout 90;
    proxy_redirect        off;

    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 Connection '';
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;
    #proxy_set_header Host $host;
  }

但在这两种方式我都得到了这个错误

"proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /path/to/config

标签: nginxhttp-proxynginx-reverse-proxynginx-config

解决方案


始终尝试在 NGINX 中使用map而不是if用于条件逻辑。除非绝对不可能map.. 在您的特定情况下,这很容易。

根据请求方法创建一个变量,该变量$backend将保存您想要的值:proxy_pass

http {
    map $request_method $backend {
        default http://10.41.115.241:8000/; 
        GET http://127.0.0.1:9101/;
    }
    ...
}

然后在你的配置中使用它:

  location /api/v1/executions {
    error_page 502 = @apiError;

    rewrite ^/api/(.*)  /$1 break;


    proxy_pass $backend;

    proxy_read_timeout    90;
    proxy_connect_timeout 90;
    proxy_redirect        off;

    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 Connection '';
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;
    #proxy_set_header Host $host;
  }

推荐阅读