2

I am trying to redirect all API calls to an authorization service endpoint using nginx. I will need to pass a custom header in which i intend to pass the original uri or $request_uri. Trying the below:

location /api/other {`
    add_header X-Original_URI $request_uri
    return 308 https://example.com/myauthservice/api/authorize
}

unfortunately the header is not getting added, need some help to see if this is correct way to do.

I tried auth_request module, proxy_pass. auth_request I cannot use, as it cannot send $request_body. Followed this, but not able store or capture the $request_body.

proxy_pass I am not able to use as it ends up like this:

https://myauthservice/api/authorize/createuser where createuser is from https://example.com/api/other/createuser

Angshuman
  • 697
  • 8
  • 29
  • Your custom header will be added to the `308 Permanent Redirect` response after the `Location` header, but that won't made the browser send that header as part of the request to `https://example.com/myauthservice/api/authorize` URI. I don't see any ways to do it but to proxy that request with the `proxy_pass` directive using something like `location /api/other { rewrite ^ / break; proxy_set_header X-Original-URI $request_uri; proxy_pass https://example.com/myauthservice/api/authorize; }`. – Ivan Shatsky Nov 27 '20 at 07:07
  • thanks for reply, this does not seem to work, throws 405 not allowed. because proxypass expects the argument. – Angshuman Nov 27 '20 at 07:18
  • But the `https://example.com/myauthservice/api/authorize` **is** an argument for `proxy_pass`, isn't it? – Ivan Shatsky Nov 27 '20 at 07:33
  • as far as i know it adds createuserat the end, if it does not see it, it is not happy. – Angshuman Nov 27 '20 at 07:42

1 Answers1

2

You can prevent appending the /createuser suffix to the proxied request. As the proxy_pass documentation states:

In some cases, the part of a request URI to be replaced cannot be determined:

...

  • When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):

    location /name/ {
        rewrite    /name/([^/]+) /users?name=$1 break;
        proxy_pass http://127.0.0.1;
    }
    

    In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

Try the following location block:

location /api/other {
    rewrite ^ /myauthservice/api/authorize break;
    proxy_set_header X-Original_URI $request_uri;
    proxy_pass https://example.com;
}
Ivan Shatsky
  • 13,267
  • 2
  • 21
  • 37