nginx在if语句中替代proxy_pass指令

时间:2018-09-21 08:31:27

标签: if-statement nginx configuration proxypass

我有以下NGINX配置:

- location /concepts {
  auth_basic "off";
  if ($http_accept ~ 'application/json') { set $isapirequest "true"; }
  if ($http_accept ~ 'application/ld\+json') { set $isapirequest "true"; }
  if ($http_accept ~ 'application/hal\+json') { set $isapirequest "true"; }
  if ( $isapirequest = "true" ) { proxy_pass http://127.0.0.1:5315/search/concepts/; }
  if ( $isapirequest != "true" ) {
  rewrite ^/concepts$ /concepts/ redirect;
  rewrite ^(.*)$ /blah$1 last;
  }
  include add_cors_headers_OPTIONS_HEAD_GET_PUT_DELETE;
  }

我得到的错误是:

\"proxy_pass\" cannot have URI part in location given by regular expression, or inside named location, or inside \"if\" statement, or inside \"limit_except\"

你们能在不使用“ if”语句的情况下在NGINX上以任何方式实现上述目标吗?

1 个答案:

答案 0 :(得分:0)

您的最后两个if语句是互斥的,因此可以消除其中的一个,这将消除您遇到的错误。

This document指示应在if上下文中的location块内使用哪些语句。您可能会考虑使用map来替换if语句中的所有语句。

例如:

map $http_accept $redirect {
    default                 1;
    ~application/json       0;
    ~application/ld\+json   0;
    ~application/hal\+json  0;
}

server {
    ...
    location /concepts {
        auth_basic "off";

        if ($redirect) {
            rewrite ^(.*)$ /blah$1 last;
        }
        proxy_pass http://127.0.0.1:5315/search/concepts;
        include add_cors_headers_OPTIONS_HEAD_GET_PUT_DELETE;
    }
    ...
}

rewrite ^/concepts$ /concepts/ redirect;语句可以移至处理location URI的/blah/concepts,并重写为rewrite ^/blah/concepts$ /concepts/ redirect;

有关更多信息,请参见this document