【问题标题】:nginx alternative for proxy_pass directive within if statementif 语句中 proxy_pass 指令的 nginx 替代方案
【发布时间】:2018-09-21 08:31:27
【问题描述】:

我有以下 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\"

你们能想到在 NGINX 上不使用“if”语句的任何方式来实现上述目标吗?

【问题讨论】:

  • 改用rewrite...last,并在不同的location 块中处理proxy_pass。
  • @Richard Smith,我刚刚更新了我的问题 - 对此感到抱歉。有什么想法吗?

标签: if-statement nginx configuration proxypass


【解决方案1】:

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

This document 指示应在location 上下文中的if 块内使用哪些语句。您可以考虑使用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; 语句可以移动到处理/blah/concepts URI 的location,并重写为rewrite ^/blah/concepts$ /concepts/ redirect;。

请参阅this document 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多