How to use a custom variable for the scheme in a rewrite rule in nginx

dustyburwell asked:

Is there a way to get nginx to treat a custom variable the same as it treats the $scheme in a rewrite rule? For instance:

rewrite ^/redirect;
# and
rewrite ^/redirect_with_scheme $scheme://;

will both result in a 302 redirect being sent to the client. However, this:

set $real_scheme $scheme;
rewrite ^/redirect_with_real_scheme $real_scheme://;

will result in a server side rewrite to a file that doesn’t necessarily exist and then a 404 to the client. For what it’s worth, this:

set $real_scheme $scheme;
rewrite ^/redirect_with_real_scheme $real_scheme:// redirect;

will give the desired result of sending a 302 to the client. Unfortunately, I have a lot of redirects set up this way and I would rather not update all of them with the redirect directive if it’s not necessary.

If it’s helpful, I’m using Nginx 1.6.2.

My answer:

The documentation states:

If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.

If you start the URL with some other variable, you will need to express the intention to redirect explicitly.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.