htmlnginxstaticnginx-configserve

nginx to serve static file but instead when i go to the route it downloads the .html


I am trying to serve a health status page for a particular route in my nginx configuration.

I have a docker file that copies the html into the correct location and have confirmed it was there.

But when I navigate to the route /en/health then i do not see the basic html page on screen when the site is up and running but it downloads the file to my desktop.

My HML file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sample site</title>
  </head>
  <body>
    <div<h1>I am a healthy page</h1>></div>
  </body>
</html>

My nginx config:

server {
    listen 8080;
    server_name  localhost;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }
    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    
    location /en/health {
        alias /usr/share/nginx/html/en/health/;
        index health.html; 
    }

    location /nginx_status {
        stub_status;

        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

How do I serve health.html as a web page in its own right from the nginx configuration?


Solution

  • First, you should move root /usr/share/nginx/html; to the server block context, as most of your location blocks are using the same document root. Even the location /en/health block appears to be using the same document root.

    Rather than relying on alias and index to find the correct file, use try_files to explicitly define the file you want to return.

    For example:

    location /en/health {
        try_files /en/health/index.html =404;
    }