Search code examples
if-statementnginxconfigurationproxypass

nginx alternative for proxy_pass directive within if statement


I've got the following NGINX configuration:

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

The error that I'm getting is:

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

Can you guys think of any way on NGINX to achieve the above without using an "if" statement?


Solution

  • Your last two if statements are mutually exclusive, so one of them can be eliminated, which would remove the error you are getting.

    This document indicates which statements should be used inside an if block within a location context. You might consider using a map to replace all but one of the if statements.

    For example:

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

    The rewrite ^/concepts$ /concepts/ redirect; statement can be moved to the location that processes the /blah/concepts URI, and rewritten as rewrite ^/blah/concepts$ /concepts/ redirect;.

    See this document for more.