Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx location with and without trailing slash

I would like to create a location which catches both http://example.com and http://example.com/ and another location which catches everything else. The first one will serve static html and the other one is for the api and other stuff. I've tried with this:

location ~ /?$ {
    root /var/www/prod/client/www;
}

location ~ /.+ {
    # https://stackoverflow.com/questions/21662940/nginx-proxy-pass-cannot-have-uri-part-in-location
    rewrite ^/(.*) /$1 break;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_connect_timeout       1s;
    proxy_send_timeout          30s;
    proxy_read_timeout          300s;
    send_timeout                300s;

    proxy_redirect off;
    proxy_pass http://backendPro;
}

But does not work. I've tried with many options in first location, but when it matches first then second is not matching and vice-versa:

location / {
location ~ \/?$ {
location ~ ^/?$ {
like image 589
Miquel Avatar asked Jun 13 '18 19:06

Miquel


1 Answers

It is actually much simpler:

location = / {
  # Exact domain match, with or without slash
}

location / {
  # Everything except exact domain match
}

Because location = / is more specific, it is always preferred if only the domain name is called (order of the location blocks does not matter).

You need regex in Nginx much less than you would think, because normal location blocks match every URL that matches the beginning, so location /bla matches every URL on the domain which starts with /bla (like /blabla, or /bla/blu, or /bla.jpg). I would mainly recommend regex if you need capturing groups and do something with those.

like image 127
iquito Avatar answered Nov 01 '22 13:11

iquito