How to use nginx if's param $1 in rewrite statement

10,822

I think the regex dollar forms only apply to the most recent regular expression. So you cannot combine the $1 of the if with the $1 of the rewrite without using set. However, there are simpler solutions for your scenario.

Firstly, if you know the host name (for example example.com), you can do the following:

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}
server { server_name example.com; ... }

On the other hand, if you don't have a specific host name in mind, you can do the following catch-all solution:

server {
    server_name ~^www\.(?<domain>.+)$;
    return 301 $scheme://$domain$request_uri;
}
server { server_name _; ... }

You can find out more about this second form here.

I don't recommend catch-all solutions because it is only meaningful to have at most one catch-all server block. If possible, use the named server solution.

Also, note that you can achieve the above redirection using the rewrite ^ destination permanent; form. All these solutions avoid using the poorly regarded if directive.

Share:
10,822
Alexey Pavlov
Author by

Alexey Pavlov

Updated on June 04, 2022

Comments

  • Alexey Pavlov
    Alexey Pavlov almost 2 years

    I have this working code in nginx config:

    if ($http_host ~* ^www\.(.+)$) {
        set $host2 $1;
        rewrite  (.*)  http://$host2$1;
    }
    

    I think that string set $host2 $1; may be omitted and $1 used in rewrite statement without defining some variables. But rewrite has own $1..$9 params.

    How I may use $1 form if in the rewrite statement?