Nginx安全措施:新增Http Basic認證及IP地址訪問限制
阿新 • • 發佈:2021-01-28
技術標籤:問題解決Nginx安全Nginx IP限制Nginx認證
1 背景
專案中的Nginx需要對外暴露一個介面,該介面必須具有一定的安全措施:- 呼叫介面必須是認證使用者才能呼叫
- 需要限制呼叫方的IP地址
2 解決
利用Nginx本身提供的module來實現安全需求:預設情況下,這兩個模組都已經編譯進去了- ngx_http_auth_basic_module:Http Basic認證
- ngx_http_access_module:IP地址限制
# 1.生成賬號和密碼(非明文密碼,密碼應該包括字母大小寫、數字和特殊字元) # 注意:windows下不支援htpasswd方式! printf "gsp:$(openssl passwd -crypt
[email protected])\n" >> htpasswd # 2.對特定Location新增Http Basic認證 # 注意auth_basic_user_file的路徑配置,如果找不到對應的檔案,會報403 # 報403錯誤時,在error.log中可以定位問題 location /test { root html/; # 新增Http Basic認證 auth_basic "Login Required"; auth_basic_user_file /etc/nginx/conf.d/htpasswd; autoindex on; charset utf-8,gbk; } # 3.對特定Location新增IP訪問控制 # 按順序匹配,只有172.18.13.125和172.18.13.124可以訪問,其它IP訪問時一律403 location /test { root html/; auth_basic "Login Required"; auth_basic_user_file /etc/nginx/conf.d/htpasswd; # 限制IP訪問 allow 172.18.13.125; allow 172.18.13.124; deny all; autoindex on; charset utf-8,gbk; }
3 擴充套件1:深入瞭解ngx_http_auth_basic_module模組
auth_basic:是提示框中的提示資訊,Chrome下沒有顯示出來,Firefox下可以顯示,效果如下: auth_basic_user_file:用來儲存Http Basic認證的使用者名稱和密碼的檔案。檔名稱中可以包含變數。絕對路徑和相對路徑都可以使用。其檔案內容格式如下:# comment
name1:password1
name2:password2:comment
name3:password3
支援的密碼型別有:推薦htpasswd
- 用crypt()函式加密;使用Apach Http Server中的htpasswd生成的;使用openssl passwd命令生成的;
- hashed with the Apache variant of the MD5-based password algorithm (apr1); can be generated with the same tools;
- specified by the “
{
scheme
}
data
” syntax (1.0.3+) as described inRFC 2307; currently implemented schemes includePLAIN
(an example one, should not be used PLAIN指的是明文,千萬別用明文),SHA
(1.3.13) (plain SHA-1 hashing, should not be used 沒有加鹽的SHA-1演算法,也不要用) andSSHA
(salted SHA-1 hashing, used by some software packages, notably OpenLDAP and Dovecot).
4 擴充套件2:深入瞭解ngx_http_access_module模組
示例:# 處理流程:按下面的順序檢查,直到第一個匹配為止。
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
上面例子的含義:
- 允許192.168.1.0/24和10.1.1.0/16網段,但是不包括192.168.1.1
- 允許2001:0db8::/32
- 其它的一律拒絕訪問