TransWikia.com

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

Server Fault Asked by dustyburwell on January 5, 2022

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 http://example.com;
# and
rewrite ^/redirect_with_scheme $scheme://example.com;

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://example.com;

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://example.com 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.

2 Answers

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.

Answered by Michael Hampton on January 5, 2022

I cannot reproduce your problem.

I tried the following minimal configuration, every rewrite working as expected (HTTP 302s):

events {
    worker_connections  1024;
}


http {
    include mime.types;
    server {
        listen       80;

        set $real_scheme $scheme;
        rewrite ^/redirect http://localhost;
        rewrite ^/redirect_with_scheme $scheme://localhost;
        rewrite ^/redirect_with_real_scheme $real_scheme://localhost;
    }
}

Could you provide me with a minimal configuration able to demonstrate the faulty rewrite rules?

Answered by Bernard Rosset on January 5, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP