当前位置: 代码网 > it编程>数据库>Mysql > Nginx访问控制及安全配置文档详解

Nginx访问控制及安全配置文档详解

2026年05月11日 Mysql 我要评论
一、文档说明本文档用于记录 nginx 服务的访问控制、密码认证及版本隐藏配置,实现指定网段免密访问、其他网段密码验证,同时隐藏 nginx 版本号以提升安 全 性,所有配置可直接复制使用,适配主流

一、文档说明

本文档用于记录 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 系统:
apt update && apt install -y apache2-utils
  • centos / rhel / rockylinux 系统:
yum install -y httpd-tools

3.1.2 生成密码文件

执行以下命令,用户名为 admin,按提示输入两次密码:

htpasswd -c /etc/nginx/.htpasswd admin

3.1.3 修正密码文件权限

chown nginx:nginx /etc/nginx/.htpasswd
chmod 644 /etc/nginx/.htpasswd

3.2 nginx 核心配置(访问控制+密码认证)

编辑站点配置文件(如 /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;
}

3.3 隐藏 nginx 版本号

编辑主配置 /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/.htpasswd
  • 新增免密网段:追加 allow x.x.x.x/24; 即可
  • 新增用户:htpasswd /etc/nginx/.htpasswd 新用户名(不加 -c)
  • 确保 /data/www 存在且权限正常

七、常见问题排查

  1. 非 34 网段直接 403,不弹密码框 → 缺少 satisfy any;
  2. 密码验证失败 403 → 密码错误或文件权限/路径错误
  3. nginx 启动失败 → 执行 nginx -t 查看语法错误
  4. 版本号仍显示 → 未在 http{} 配置 server_tokens off; 或未重启

八、总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com