Nginx always serve same response

nginx

For a website just-to-be-put live, we often have a static index.html in our web root. The file contains all styles and images inline, so there is no other request required to load that page.

For now, I use this config:

# Temporary placeholder
server {
        server_name .domain.com;
        root        /var/www/domain/production/public;

        index index.html;
        charset UTF-8;
}

# Production
server {
        server_name test.domain.com;
        root        /var/www/domain/production/public;

        charset UTF-8;
        gzip_types text/plain application/xml text/css text/js image/svg+xml text/xml application/x-javascript text/javascript application/json application/xml+rss;
        location /assets/images {
           default_type image/jpeg;
           expires max;
           add_header Pragma public;
           add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }
        location /styles/fonts {
           expires max;
           add_header Pragma public;
           add_header Cache-Control "public, must-revalidate, proxy-revalidate";
        }

        include conf.d/common.conf.inc;
}

This works great "enough" but ppl are able to request resources which should not be served (e.g. domain.com/foo/bar/file.ext) as only the "index" directive is set.

Question: how can I point all requests to the index.html in the first server block? I tried using a location with try_files but nginx cannot handle a single item in that list:

location / {
    try_files index.html;
}

How can I achieve this? (I know you can work with redirects, but for now I don't prefer that solution. domain.com/foo/bar/baz should just serve index.html).

Best Answer

I think you need this:

location = /index.html {
    root /var/www/domain/production/public;     
}
location / {
    rewrite . /index.html last;
}

See Nginx's documentation on location to see what it means.