Nginx – How to configure a location block to always return a single file in nginx

configurationnginx

In my application I want the location "/" to return a static index.html file, I want "/static" to serve static files from a folder and I want all other requests to return 404 NOT FOUND. At a later point I'm going to redirect all other requests to a WSGI server.

This is currently my configuration:

# Dev server.
server {
    listen 1337;
    charset UTF-8;

    location / {
        rewrite ^ static/index_debug.html break;
    }

    location /static {
        alias /home/tomas/projects/streamcore/static;
    }
}

The static folder is working perfectly, but "/" is returning 404 NOT FOUND. I have also tried:

alias /home/tomas/projects/streamcore/static/index_debug.html;

In the location block, but that returns 500 INTERNAL SERVER ERROR. It seems like alias doesn't like single files. Additionally I've tried:

try_files static/index_debug.html;

But that stops the server from starting with the error "invalid number of arguments in try_files directive". Apparently try_files actually requires you to try more than one file, which is not the behaviour I'm looking for.

So my question is: How so I configure a location block to always return a static file?


EDIT: I've seen from other answers that alias should indeed accept a single file as argument, so I tried:

location = / {
    alias /home/tomas/projects/streamcore/static/index_debug.html;
}

But I still only get 500 INTERNAL SERVER ERROR. The error log for the "/" request says:

[alert] 28112#0: *7 "/home/tomas/projects/streamcore/static/index_debug.htmlindex.html" is not a directory

Why is it trying to open "index_debug.htmlindex.html"? I'm not using the index directive anywhere.

Best Answer

Just tested this and it works for me:

server {
    root /tmp/root;
    server {
        listen 8080;
        location /static {
            try_files $uri =404;
        }
        location / {
            rewrite ^ /static/index_debug.html break;
        }
    }
}

The file /tmp/root/static/index_debug.html exists of course :)

I can hit any URL and I just get the static page.