Restricting Access to Sensitive Files and Directories with Nginx
This guide explains how to use Nginx configuration directives to deny execution of uploaded scripts, block access to specific file types and directories, return custom HTTP status codes, and limit access by client IP to improve web server security.
Controlling user permissions on a server is crucial; by configuring Nginx to forbid execution of uploaded PHP, shell, Python, and other script files, you can prevent malicious use of uploaded resources and strengthen site security.
1. Deny parsing of specific program files in designated directories:
location ~ ^/images/.*\.(php|php5|\.sh|\.pl|\.py)$ {
deny all;
}
location ~ ^/static/.*\.(php|php5|\.sh|\.pl|\.py)$ {
deny all;
}
location ~* ^/data/(attachment|avatar)/.*\.(php|php5)$ {
deny all;
}2. Block access to certain file extensions under Nginx’s root directory:
location ~*\.(txt|doc)$ {
if (-f $request_filename) {
root /data/www/www;
# optional rewrite can be added here
break;
}
}
location ~*\.(txt|doc)$ {
root /data/www/www;
deny all;
}Note: If you have a separate PHP matching block, place the above deny rules before the PHP block to ensure they take effect.
Typical PHP fastcgi handling (shown for context):
location ~.*\.(php|php5)?$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}3. Deny access to specific directories or path patterns:
location ~ ^/(sub)/ {
deny all;
}
location ~ ^/sub {
deny all;
}You can also return explicit HTTP status codes for prohibited directories:
location /usr/local/nginx/ {
return 404;
}
location /templates/ {
return 403;
}4. Restrict access by client IP address:
location ~ ^/order/ {
allow 182.61.200.6;
deny all;
}
if ( $remote_addr = 182.61.200.61 ) {
return 403;
}
if ( $remote_addr = 182.61.200.6 ) {
set $allow_access_root 'true';
}Using if statements allows you to create IP whitelists for more granular control.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
