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.
1 Answer
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.
proxy_redirectstatements in a block, but can you give an example of what you are trying to achieve?