Nginx Restrict Access to File
10,353
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.
Author by
Samast Varma
Updated on June 04, 2022Comments
-
Samast Varma almost 2 years
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?
-
Tarun Lalwani almost 6 yearson what url you are able to access and what is the rest of the config?
-
Samast Varma almost 6 yearsI've updated my question with answers to your question.
-
Tarun Lalwani almost 6 yearsCan you move the whole
/credential.js
block insidelocation /
? and try again -
Samast Varma almost 6 yearsThat didn't fix it. Same results.
-
Tarun Lalwani almost 6 yearsRun
nginx -T
and the output to your question -
Samast Varma almost 6 yearsThat command just outputted the configurations I have saved for my server, one of which is the one I posted above. Anything specific you want me to do with that?
-
Tarun Lalwani almost 6 yearsSo this is the only virtual server you have configured in nginx? How did you reload the config? Can you run
nginx -s reload
-
Samast Varma almost 6 yearsIssue is fixed. Thank you!
-
-
nbari almost 6 years@SamastVarma try the small example in the answer that should work, if required just change the server_name/port.
-
hcheung almost 6 years'Still not working', did you forgot to reload the nginx configuration after changing?
location = /credentials.js
orlocation ~* credentials.js
should deny the access of the file. -
Samast Varma almost 6 yearsI updated my code last night with the
=
and reloaded but was still able to access the file from the web. I tried again this morning and it's correctly returning a 404. Thank you! -
heinels almost 2 yearsIt works. You need to clear your browser cache. Otherwise, you still can download the file which you don't want others to access.