Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx rewrite syntax

I've seen a bunch of ngnix rewrites that have syntax like this:

server {
    server_name  www.example.com;
    rewrite ^(.*) http://example.com$1 permanent;
}

I don't understand the ^(.*) part. Does the ^ take everything after the TLD of the uri?

like image 724
Tyler DeWitt Avatar asked Apr 01 '26 11:04

Tyler DeWitt


2 Answers

The ^ does indeed match at the beginning of the string. In the case of nginx's rewrite directive this means the beginning of the path component of the actual URI. Unfortunately nginx's documentation is slightly incorrect. Quoting from http://www.nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite :

If the specified regular expression matches a URI, the URI is changed as specified in the replacement string.

However, this is technically wrong. rewrite does not match the whole URI/URL but only its path component (which always starts with a / even if the user only enters e.g. http://www.example.com instead of http://www.example.com/). Therefore rewrite ^(.*) http://example.com$1 permanent; does not turn into http://example.comwww.example.com.

If I remember it correctly, the ^ just sets the Regex rule to match the start of the string. The parentheses are used to extract that part with the $1-9 variables.

Another solution from the Nginx wiki. Link

server {
   server_name www.example.com;
   rewrite ^ http://example.com$request_uri? permanent;
}
like image 36
ChristofferH Avatar answered Apr 08 '26 05:04

ChristofferH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!