Restricting Access and Enhancing Website Security with Nginx Configuration
This guide explains how to use Nginx directives to deny execution of uploaded script files, block specific file types, restrict directory access, and limit client IPs, thereby strengthening website security for user‑facing services.
For most companies serving users, controlling user permissions is crucial; configuring Nginx to block execution of uploaded scripts such as PHP, shell, or Python files strengthens website 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 types in Nginx’s root directory:
location ~* \.(txt|doc)$ {
if (-f $request_filename) {
root /data/www/www;
# optional rewrite can redirect a URL
break;
}
}Note: If a PHP matching block exists, place the above deny rules before the PHP block.
location ~.*\.(php|php5)?$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}3. Deny access to specific directories or paths:
location ~ ^/(static)/ {
deny all;
}
location ~ ^/static {
deny all;
}
location /admin/ {
return 404;
}
location /templates/ {
return 403;
}4. Restrict access by client IP, allowing only certain IPs to a directory while denying others:
location ~ ^/order/ {
allow 219.141.140.10;
deny all;
}
if ($remote_addr = 219.141.140.11) {
return 403;
}
if ($remote_addr = 219.141.140.12) {
set $allow_access_root 'true';
}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.
