4

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).

4
  • What do you want nginx to do when a URI without a trailing / points to a directory? At the moment $uri/ tells it to issue a 3xx response, and the listen directive tells it to use port 80 in the redirect. Commented Aug 3, 2018 at 9:25
  • @RichardSmith I want both localhost:8000/app and localhost:8000/app point to the same place (the index.html) Commented Aug 3, 2018 at 12:18
  • The redirect is caused by $uri/ in the try_files statement. You could just remove it. Commented Aug 3, 2018 at 12:22
  • @RichardSmith, are you suggesting putting only try_files $uri /app/index.html?$args;? can you post it as an answer - for it to be excepted Commented Aug 3, 2018 at 12:40

2 Answers 2

8

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It didn't help. I am still being redirected to http://localhost/app/ after going to http://localhost:8000/app - still http://localhost:8000/app/ works as expected
Did you restart nginx, and did you clear the browser cache?
0

All you need is this:

 port_in_redirect on;

But watch out for forward ports if you want your server to be public.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.