Krunal
Krunal

Reputation: 3277

Use script instead of regex for Nginx prox_redirect to modify Location header

For Nginx, proxy_redirect, can we use a string instead of string or regex? I have a need to replace multiple occurrences of text in the Location string using proxy_redirect and I am not sure how to do it with regex. Therefore, I am checking if the proxy_redirect can make us of script, then it could be easy.

Upvotes: 1

Views: 584

Answers (1)

Richard Smith
Richard Smith

Reputation: 49812

You can use multiple proxy_redirect statements within a single block containing the proxy_pass statement. Nginx evaluates statements containing regular expressions in order until a match is found, so place the more specific regular expressions before the less specific ones.

To replace a single occurrence of a pattern within the Location header of a 3xx response, you would use:

proxy_redirect ~^(.*)origin.example.com(.*)$ $1main.example.com$2;

To replace two occurrences of the same pattern, you would use:

proxy_redirect ~^(.*)origin.example.com(.*)origin.example.com(.*)$ $1main.example.com$2main.example.com$3;

To replace one, two or three occurrences of the same pattern, you would use:

proxy_redirect ~^(.*)origin.example.com(.*)origin.example.com(.*)origin.example.com(.*)$ $1main.example.com$2main.example.com$3main.example.com$4;
proxy_redirect ~^(.*)origin.example.com(.*)origin.example.com(.*)$ $1main.example.com$2main.example.com$3;
proxy_redirect ~^(.*)origin.example.com(.*)$ $1main.example.com$2;

Use ~* to make the regular expression case-insensitive. See this document for details.

Upvotes: 1

Related Questions