how to serve html files in nginx without showing the extension in this alias setup
Asked Answered
S

2

36

I'm having a lot of trouble setting up this alias inside nginx to display my website correctly.

The website I'm concerned with should be accessible from mywebsite.com/mr and is different from the site located at mywebsite.com/. The website is located at /fullpath (shortened for simplicity) The site needs to serve three kinds of content:

  1. The index file located in /fullpath/index.html.
  2. Other html files (without showing the .html extension in the browser).
  3. Static assets (js/css/img) located in /fullpath and subdirectories.

I've tried changing around the order of matches in the try_files and found situations where they all worked, just not at the same time:

location /mr {
  default_type "text/html";
  alias /fullpath;

  # with this one 1 and 3 work
  # try_files $uri/index.html $uri.html $uri; 

  # with this one 2 and 3 work
  # try_files $uri $uri.html $uri/index.html;

  # with this one 1 and 2 work
  try_files $uri.html $uri/index.html $uri;
}

When one doesn't work it 404's. Does anybody know how I can serve all kinds of files correctly?

Schnurr answered 16/3, 2013 at 15:42 Comment(0)
G
50

Apparently alias and try_files don't work together. However, I don't think you need to use alias.

location /mr {
  default_type "text/html";
  try_files  /fullpath/$uri /fullpath/$uri.html /fullpath/$uri/index.html  /fullpath/index.html;
}

Which would try:

  • Exact file.
  • File with .html added.
  • Index in the path.
  • Default index.

I think the root directive does work with try files but am unable to test.

server{
    location /mr {

        root /home/mysite/fullpath;

        default_type "text/html";
        try_files  $uri $uri.html $uri/index.html index.html;
    }
}
Garibald answered 17/3, 2013 at 1:34 Comment(1)
Following the bottom example is changing 404 errors into 500 errors, the error logs shows *20172 rewrite or internal redirection cycle while internally redirecting to "index.html", client: , I ha to follow the steps shown in serverfault.com/questions/660986/… to fix this 500 errorLamblike
J
18

I used a combo of what @Danack posted which led me to the result I was looking for (serve the html file directly):

location /health-check {
    default_type "text/html";
    alias /path/to/my/file.html;
}
Jenine answered 11/5, 2015 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.