Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx Restrict Access to File

Tags:

nginx

ubuntu

Currently my config file (/etc/nginx/sites-available/default) says

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location /credentials.js {
                deny all;
                return 404;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

}

but I can still access credentials.js via example.com/credentials.js from the web. Any suggestions?

like image 644
Samast Varma Avatar asked Oct 30 '25 10:10

Samast Varma


1 Answers

Try adding a = to your location, that will do an exact match:

server {
    server_name _;
    listen 80 default_server;

    location = /credentials.js {
        deny all;
        return 404;
    }

    location / {
        add_header Content-Type text/plain;
        return 200 "hello world\n\n";
    }
}

From the nginx location docs:

If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.

like image 110
nbari Avatar answered Nov 03 '25 00:11

nbari