75人参与 • 2026-05-11 • Mysql
本文档用于记录 nginx 服务的访问控制、密码认证及版本隐藏配置,实现指定网段免密访问、其他网段密码验证,同时隐藏 nginx 版本号以提升安 全 性,所有配置可直接复制使用,适配主流 linux 系统(centos、ubuntu 等)。
apt update && apt install -y apache2-utils
yum install -y httpd-tools
执行以下命令,用户名为 admin,按提示输入两次密码:
htpasswd -c /etc/nginx/.htpasswd admin
chown nginx:nginx /etc/nginx/.htpasswd chmod 644 /etc/nginx/.htpasswd
编辑站点配置文件(如 /etc/nginx/conf.d/default.conf),替换 location / 块:
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;
}
编辑主配置 /etc/nginx/nginx.conf,在 http {} 中添加:
http {
# 隐藏版本号
server_tokens off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 其他原有配置不变
}
进阶(彻底隐藏 server 标识):
http {
server_tokens off;
more_set_headers "server: my-server";
}
# 检查配置语法 nginx -t # 重启生效 systemctl restart nginx
| 访问ip/网段 | 预期效果 | 验证方法 |
|---|---|---|
| 192.168.34.* | 直接访问,不弹密码框 | 该网段电脑/服务器访问站点 |
| 非 192.168.34.* | 弹出密码框,验证失败返回 403 | 手机热点/其他网段设备访问 |
| 任意ip | 响应头无 nginx 版本号 | 浏览器 f12 network 查看 server 头 |
/etc/nginx/.htpasswdallow x.x.x.x/24; 即可htpasswd /etc/nginx/.htpasswd 新用户名(不加 -c)/data/www 存在且权限正常satisfy any;nginx -t 查看语法错误http{} 配置 server_tokens off; 或未重启以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论