Nginx——基於站點目錄和文件的URL訪問控制
對於為用戶服務的大多數公司而言,把控用戶權限是一件十分重要的事情。通過配置Nginx來禁止訪問上傳資源目錄下的PHP、shell、Python等程序文件,這樣用戶即使上傳了這些文件也沒法去執行,以此來加強網站安全。
1. 限制禁止解析指定目錄下的制定程序
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. 禁止訪問Nginx的root根目錄下的某些文件
location ~*.(txt|doc)${ if (-f $request_filename) { root /data/www/www; #還可以使用"rewrite ...."重定向某個URL break; } } location ~*.(txt|doc)${ root /data/www/www; deny all; }
需要注意:如果有php匹配配置,上面的限制配置應該放在php匹配的前面
location ~.*.(php|php5)?${ fastcgi_pass 127.0.0.1:9000 fastcgi_index index.php include fcgi.conf; }
3. 禁止指定目錄或path匹配的訪問
location ~ ^/(static)/ { deny all; } location ~ ^/static { deny all; } #禁止訪問目錄並返回指定的http狀態碼 location /admin/ { return 404; } location /templates/ { return 403; }
4. 限制網站來源IP訪問。比如禁止某目錄讓外界訪問,但允許某IP訪問該目
location ~ ^/order/ { allow 172.16.60.23; deny all; }
還可以使用if來限制客戶端ip訪問(即添加白名單限制)
if ( $remote_addr = 172.16.60.28 ) { return 403; } if ( $remote_addr = 172.16.60.32 ) { set $allow_access_root 'true'; }
Nginx——禁止IP/非法域名訪問
在生產環境中,為了網站的安全訪問,需要Nginx禁止一些非法訪問,如惡意域名解析,直接使用IP訪問網站。下面記錄一些常用的配置示例:
1)禁止IP訪問,如果沒有匹配上server name就會找default默認,返回501錯誤。
server { listen 80 default_server; server_name _; return 501; }
2)通過301跳轉到主頁
server { listen 80 default_server; server_name _; rewrite ^(.*) http://www.kevin.com/$1 permanent; }
3)凡是請求kevin.bao.com 都跳轉到后面域名grace.ru.com上。(需要放到server配置里)
if ($host ~ '^kevin.bao.com'){ return 301 https://grace.ru.com$request_uri; }
