一、文档说明
本文档用于记录 Nginx 服务的访问控制、密码认证及版本隐藏配置,实现指定网段免密访问、其他网段密码验证,同时隐藏 Nginx 版本号以提升安全性,所有配置可直接复制使用,适配主流 Linux 系统(CentOS、Ubuntu 等)。
二、核心配置需求
- 192.168.34.0/24 网段:免密码直接访问网站根目录
- 非 192.168.34.0/24 网段(含 192.168.35.*、外网 IP 等):需输入账号密码验证,验证失败/未输入则返回 403 禁止访问
- 隐藏 Nginx 版本号,避免版本漏洞泄露,提升服务安全性
- 网站根目录:/data/www,默认索引页为 index.html、index.htm,支持单页应用路由(try_files 配置)
三、详细配置步骤
3.1 密码文件生成(/etc/nginx/.htpasswd)
3.1.1 安装密码生成工具
- Debian / Ubuntu 系统:
bash
apt update && apt install -y apache2-utils
- CentOS / RHEL / RockyLinux 系统:
bash
yum install -y httpd-tools
3.1.2 生成密码文件
执行以下命令,用户名为 admin,按提示输入两次密码:
bash
htpasswd -c /etc/nginx/.htpasswd admin
3.1.3 修正密码文件权限
bash
chown nginx:nginx /etc/nginx/.htpasswd
chmod 644 /etc/nginx/.htpasswd
3.2 Nginx 核心配置(访问控制+密码认证)
编辑站点配置文件(如 /etc/nginx/conf.d/default.conf),替换 location / 块:
nginx
location / {
# 满足任一条件即可访问(免密网段 或 密码验证)
satisfy any;
# 允许指定网段免密访问
allow 192.168.34.0/24;
# 禁止其他未验证 IP
deny all;
# 基础认证配置
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 站点根目录与首页
root /data/www;
index index.html index.htm;
# SPA 路由支持
try_files $uri $uri/ /index.html last;
}
3.3 隐藏 Nginx 版本号
编辑主配置 /etc/nginx/nginx.conf,在 http {} 中添加:
nginx
http {
# 隐藏版本号
server_tokens off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 其他原有配置不变
}
进阶(彻底隐藏 Server 标识):
nginx
http {
server_tokens off;
more_set_headers "Server: My-Server";
}
四、配置生效命令
bash
# 检查配置语法
nginx -t
# 重启生效
systemctl restart nginx
五、效果验证
| 访问IP/网段 | 预期效果 | 验证方法 |
|---|---|---|
| 192.168.34.* | 直接访问,不弹密码框 | 该网段电脑/服务器访问站点 |
| 非 192.168.34.* | 弹出密码框,验证失败返回 403 | 手机热点/其他网段设备访问 |
| 任意IP | 响应头无 Nginx 版本号 | 浏览器 F12 Network 查看 Server 头 |
六、注意事项
- 密码文件必须使用绝对路径
/etc/nginx/.htpasswd - 新增免密网段:追加
allow x.x.x.x/24;即可 - 新增用户:
htpasswd /etc/nginx/.htpasswd 新用户名(不加 -c) - 确保
/data/www存在且权限正常
七、常见问题排查
- 非 34 网段直接 403,不弹密码框 → 缺少
satisfy any; - 密码验证失败 403 → 密码错误或文件权限/路径错误
- Nginx 启动失败 → 执行
nginx -t查看语法错误 - 版本号仍显示 → 未在
http{}配置server_tokens off;或未重启