Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nginx

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?

like image 813
Alexey Pavlov Avatar asked Sep 14 '25 15:09

Alexey Pavlov


1 Answers

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.

like image 173
Kevin A. Naudé Avatar answered Sep 16 '25 12:09

Kevin A. Naudé