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;
# 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.

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!

Related Questions

Preset runtime parameters for a docker container

1  Asked on November 4, 2021 by ormfo4i5fm


terraform – shall one use simple disk or linux LVM?

0  Asked on November 4, 2021 by wojtas-zet


GCP – Quickstart: Build and Deploy Problems

1  Asked on November 4, 2021 by ajiroghene


how to setup Carton, to compile znapzend 0.20.0?

1  Asked on November 4, 2021 by crestop


Recover data from IBM x3650 with SYS BRD ERR

1  Asked on November 4, 2021 by maxxer


cloning NTFS disk

1  Asked on November 4, 2021 by lucio-crusca


Apache Link to PHP run application/x-httpd-php *

1  Asked on February 28, 2021 by wobbo


uwsgi, multiple environment variables

2  Asked on February 25, 2021 by user204088


Ask a Question

Get help from others!

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