Query Strings in Redirects

Nov 4, 2021

I recently had to change the URLs of some of my REST endpoints in a project at work. In so doing, I started receiving reports of users who weren't seeing the data they expected from some endpoints. My redirect seemed simple enough:

location ~* ^/rest/(report/.*)$ {
    return 302 https://$host/rest/project/$1;
}

So, I'm sending URLs like https://myhostname/rest/report/1/ to https://myhostname/rest/project/report/1/. The redirect worked, but the problem was that any additional query string that was included in the URL got dropped.

For example, https://myhostname/rest/report/1/?query=somevalue would result in https://myhostname/rest/project/report/1/. The fix for this is easy, but is something I didn't realize you had to pay attention to:

location ~* ^/rest/(report/.*)$ {
    return 302 https://$host/rest/project/$1$is_args$args;
}

The $is_args directive will return a ? if there are arguments, or an empty string otherwise. Similarly, $args will return any arguments that happened to be passed. Including these variables ensures that any query parameters get passed along with the redirect.

0 Comments
Add a Comment
Ignore this field:
Leave this blank:
Optional; will not be indexed
Ignore this field:
Both Markdown and a limited set of HTML tags are supported
Leave this empty: