Angshuman
Angshuman

Reputation: 707

Add a custom header while redirecting in NGINX

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

Upvotes: 3

Views: 3168

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15687

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

Upvotes: 2

Related Questions