84

I have several sets of static .html files on my server, and I would like use nginx to serve them directly. For example, nginx should serve an URI of the following pattern:

www.mysite.com/public/doc/foo/bar.html

with the .html file that is located at /home/www-data/mysite/public/doc/foo/bar.html. You can think of foo as the set name, and bar as the file name here.

I wonder whether the following piece of nginx config would do the job:

server {
    listen        8080;
    server_name   www.mysite.com mysite.com;
    error_log     /home/www-data/logs/nginx_www.error.log;
    error_page    404    /404.html;

    location /public/doc/ {
        autoindex         on;
        alias             /home/www-data/mysite/public/doc/;
    }

    location = /404.html {
        alias             /home/www-data/mysite/static/html/404.html;
    }
}

In other words, all requests of the pattern /public/doc/.../....html are going to be handled by nginx, and if any given URI is not found, a default www.mysite.com/404.html is returned.

MLister
  • 9,252
  • 17
  • 59
  • 89

1 Answers1

119

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}
dipole_moment
  • 4,266
  • 2
  • 38
  • 55
cobaco
  • 9,702
  • 6
  • 34
  • 32
  • 1
    Using 2 roots gave me problems in the past, what I usually do is use one root and alias for other locations as @AlessioCampanelli suggests – camposer Apr 11 '20 at 11:42