1

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.

5
  • You can use several proxy_redirect statements in a block, but can you give an example of what you are trying to achieve? Commented Sep 1, 2020 at 6:11
  • Here is another question that describes overall problem I am trying to solve with proxy_redirect. stackoverflow.com/questions/63647067/… Commented Sep 1, 2020 at 6:12
  • With single occurrence of text to change in a string, regex works, but with multiple occurrences regex is not possible. And I think if it supports script then it can be done easily. Commented Sep 1, 2020 at 6:13
  • How many occurrences of the string are there likely to be? You could write a regex to handle one occurrence, and another to handle two occurrences, etc. Commented Sep 1, 2020 at 6:36
  • There are three occurrences as of now. Any hint or reference how to do this is great! Commented Sep 1, 2020 at 6:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

wow, this works fine. I got an exact idea. Thanks for guiding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.