Nginx proxy pass based on http method

2019-07-30 16:21发布

问题:

Is it possible to filter OPTIONS calls from a location and redirect them somewhere else? Tried this configuration but didn't work:

  location /example/ {
    proxy_pass http://example.com;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass_request_headers  on;

    limit_except OPTIONS {
      proxy_pass http://anotherurl.com;
    }
  }

回答1:

There are several ways this can be achieved. The easiest one, in my opinion, is with the map directive:

upstream some_backend {
    server example.com;
}

upstream another_backend {
    server anotherurl.com;
}

map $request_method $upstream {
    default some_backend;
    OPTIONS another_backend;
}

server {
    ...
    location /example/ {
        ...
        proxy_pass http://$upstream;
        ...
    }
    ...
}

Using upstreams is not mandatory but recommended. In most cases it will make your configuration easier to read, maintain and extend. Nevertheless, if you prefer to omit the upstream blocks and write your hosts directly in the map block, the configuration will still work:

map $request_method $upstream {
    default example.com;
    OPTIONS anotherurl.com;
}


标签: nginx