Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx missing trailing slash returns 301

I have the following config:

server {
  listen       80;
  server_name  localhost;

  location  /app {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /app/index.html?$args;
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}

When navigating to http://localhost:8000/app/ all works as expected but when removing the trailing slash (http://localhost:8000/app) nginx returns 301 status response and I am being redirected to http://localhost/app.

How can I make nginx work with both http://localhost:8000/app/ and http://localhost:8000/app (with and without trailing slash).

like image 351
vlio20 Avatar asked Oct 20 '25 14:10

vlio20


1 Answers

The $uri/ term in the try_files statement causes nginx to append a trailing / to the requested URI, if that URI resolves to a local directory. See this document for more.

The trailing / is appended by issuing a 3xx response, and of course nginx gets the port wrong as it knows nothing about port 8000.

If you do not want nginx to issue any 3xx responses, simply remove the $uri/ term from your try_files statement.

For example:

location  /app {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri /app/index.html?$args;
}
like image 185
Richard Smith Avatar answered Oct 22 '25 02:10

Richard Smith



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!