1

I am trying to redirect users to a new URL while preserving the URL query parameters. I'm trying this, which doesn't pass the URL params:

location = /api/redirects {
  return 301 /api2/redirects;
}
https://example.com/api/redirects?param=1&anotherParam=10

  => https://example.com/api2/redirects

I also tried:

location = /api/redirects {
  return 301 /api2/redirects$is_args$args;
}
2
  • Did you restart Nginx after making the configuration change and did you reset the browser cache. Your $is_args$args fix should work. Rather than relying on the browser, test it using curl -I http://example.com/api/redirects Commented Nov 30, 2021 at 19:52
  • @LearningPath In opposite to return directive, rewrite one will preserve any existing query arguments: rewrite ^ /api2/redirects permanent; Commented Nov 30, 2021 at 19:55

1 Answer 1

1

You can use rewrite explicitly outside of a location block. RegEx parentheses can capture URI values after /api/ as $1. The query string is always passed in a rewrite directive.

# 302 Moved Temporarily
rewrite ^/api/(redirects.*) /api2/$1 redirect;
# 301 Moved Permanently
rewrite ^/api/(redirects.*) /api2/$1 permanent;
Sign up to request clarification or add additional context in comments.

Comments

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.