Nginx提供了多种方式来控制访问权限,可以根据IP地址、用户认证、地理位置等多种方式进行访问限制。以下是几种常用的限制指定用户访问的方法:
location /restricted/ {
allow 192.168.1.100; # 允许的IP
allow 10.0.0.0/24; # 允许的IP段
deny all; # 拒绝其他所有IP
}
sudo htpasswd -c /etc/nginx/.htpasswd username
(系统会提示输入密码)
location /private/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /admin/ {
allow 192.168.1.100; # 只允许特定IP
deny all; # 拒绝其他IP
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
首先确保安装了GeoIP模块,然后:
geo $allowed_country {
default no;
US yes; # 允许美国
CA yes; # 允许加拿大
}
server {
location / {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
location /downloads/ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
location /api/ {
limit_except GET POST {
deny all;
}
}
deny all
作为默认策略,然后明确列出允许的例外sudo nginx -t && sudo nginx -s reload
需要针对特定场景的详细配置方案,可以提供更多具体需求信息。