在CentOS上配置Nginx的訪問控制,可以通過以下幾種方式實現:
使用allow
和deny
指令來控制訪問。
server {
listen 80;
server_name example.com;
location / {
allow 192.168.1.1; # 允許特定IP訪問
deny all; # 拒絕其他所有IP訪問
root /var/www/html;
index index.html index.htm;
}
}
使用auth_basic
和auth_basic_user_file
指令來實現基本認證。
首先,創建一個包含用戶名和密碼的文件:
sudo htpasswd -c /etc/nginx/.htpasswd username
然后在Nginx配置中使用:
server {
listen 80;
server_name example.com;
location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
root /var/www/html;
index index.html index.htm;
}
}
使用allow
和deny
指令結合geo
模塊來實現更復雜的IP訪問控制。
geo $allowed {
default 0;
192.168.1.0/24 1; # 允許192.168.1.0/24網段
}
server {
listen 80;
server_name example.com;
location / {
if ($allowed = 0) {
return 403 "Forbidden";
}
root /var/www/html;
index index.html index.htm;
}
}
如果你使用的是Nginx Plus,可以利用其動態訪問控制功能,通過外部服務進行認證。
server {
listen 80;
server_name example.com;
location / {
auth_request /auth;
root /var/www/html;
index index.html index.htm;
}
location = /auth {
internal;
proxy_pass http://auth_service/auth;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
}
結合iptables或firewalld來控制訪問。
sudo iptables -A INPUT -p tcp --dport 80 -s 192.168.1.1 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j DROP
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.1" port protocol="tcp" port="80" accept'
sudo firewall-cmd --reload
根據你的具體需求,可以選擇適合的訪問控制方式?;驹L問控制和基于用戶名密碼的認證是最常用的方法,而ACL和動態訪問控制則適用于更復雜的場景。結合防火墻規則可以進一步增強安全性。