Search code examples
.netnginxconfigurationstatic-files

Site configuration under NGINX: serve static files and .NET files


I'm trying to get Nginx to serve static content and forward it to .NET too. Sorry if this is simple, I'm new to nginx.

This is my sites-available file:

server {
    listen 80;
    server_name ip_here domain_here;
    root /var/www/html;

    location ^~ /static/ {
        try_files $uri $uri/ cat.txt =404;
    }

    location / {
        try_files @dotnet /dev/null dog.txt =404;
    }

    location @dotnet {
        #...
    }

    ##NOTE: THE FOLLOWING WORKED BEFORE I CHANGED IT TO THE ABOVE
    ##location / {
    ##    try_files $uri $uri/ @dotnet;
    ##}
}

I changed the commented part to the uncommented part because (1) I needed example.com/ to direct to @dotnet but try_files / obviously worked, and (2) people pointed out it was more secure to have a /static/.

When I try to access any path, I get a 404, not even the debug dog.txt or cat.txt.

Thanks in advance.


Solution

  • You have a location ^~ /static/ block which processes any URI which begins with /static/. The try_files directive will test file parameters in order to determine if a local file exists at calculated pathname. The pathname is calculated by concatenating the value of the root directive with the value of the *file parameter. These file parameters should begin with a leading /.

    In this case:

    root /var/www/html;
    location ^~ /static/ {
        try_files $uri $uri/ /cat.txt =404;
    }
    

    The URI /static/foo will be tested to see if a file exists at /var/www/html/static/foo, then a directory at /var/www/html/static/foo, then a file at /var/www/html/cat.txt, and finally take the default action of returning a 404 status.

    Only the last parameter of the try_files directive can be status code, named location, or a URI (causing an internal redirection). See this document for details.

    If cat.txt is located at /var/www/html/static/cat.txt, use:

    try_files $uri $uri/ /static/cat.txt =404;
    

    Notice that in both cases, there is a leading /.

    If there is no directory called static, use the alias directive instead. But note that alias and try_files in the same location block, can cause problems.


    In this case:

    try_files @dotnet /dev/null dog.txt =404;
    

    The try_files statement makes no sense. The named location can only appear in the last position. So the last parameter can be a named location or an =404, not both.

    There is no need for a location / block sending the request to a location @dotnet. Just remove the location / block and rename the location @dotnet block to location /.