保護 phpmyadmin、download 等敏感目錄,僅允許內網 IP(如 192.168.1.0/24)存取,外網 IP 直接拒絕。
Nginx location 匹配優先順序:
= 精確匹配^~ 前綴匹配(不再嘗試正則)~/~* 正則匹配/ 通用匹配使用 ^~ /phpmyadmin/ 確保優先於通用 location / 與 PHP 正則 location 生效,避免被後者攔截導致 404/500。
server {
listen 80;
server_name example.com;
access_log logs/access.log main;
# 通用站點根目錄
location / {
root html;
index index.php index.html index.htm;
}
# 受保護目錄:phpmyadmin
location ^~ /phpmyadmin/ {
allow 192.168.1.0/24; # 允許內網
deny all; # 拒絕其餘
# 內層處理 PHP
location ~ \.php$ {
root /var/mailapp/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
# 通用 PHP 處理
location ~ \.php$ {
root /opt/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
server {
listen 80;
server_name example.com;
access_log logs/access.log main;
location / {
root html;
index index.php index.html index.htm;
}
location ^~ /download/ {
allow 192.168.1.0/24;
deny all;
index index.php index.html index.htm;
location ~ \.php$ {
root /var/mailapp/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
location ~ \.php$ {
root /opt/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
| 問題 | 原因 | 解法 |
|---|---|---|
| 受保護目錄下 PHP 回傳 404 | 外層 location ~ \.php$ 搶先匹配,root 指向錯誤路徑 | 在受保護目錄 location 內再定義一層 location ~ \.php$ |
| 允許 IP 仍被拒絕 | IP 格式錯誤或 CIDR 寫法不支援 | 確認用 192.168.1.0/24 格式,或單一 IP 192.168.1.100 |
| 修改後不生效 | 未重新載入 Nginx | nginx -t && nginx -s reload |
# 測試內網 IP(應回傳 200/403 視目錄權限)
curl -I https://example.com/phpmyadmin/
# 測試外網 IP(應回傳 403)
curl -I --interface eth0 https://example.com/phpmyadmin/