一、原理说明

Nginx 默认会在响应头(如Server错误页面中显示具体版本号(如nginx/1.21.6)。隐藏版本号的核心是通过配置关闭版本信息的显示,仅保留软件名称(如Server: nginx)。

二、具体配置步骤

1. 打开 Nginx 主配置文件

Nginx 的主配置文件通常名为nginx.conf,位置因安装方式不同而有所差异:

  • 源码编译安装:一般在 /usr/local/nginx/conf/nginx.conf

  • 包管理工具安装(如 apt/yum):一般在 /etc/nginx/nginx.conf

使用文本编辑器打开:

vim /etc/nginx/nginx.conf  # 根据实际路径修改

2. 添加隐藏版本号的配置

http块中添加server_tokens off;指令:

nginx

http {
    include       mime.types;
    default_type  application/octet-stream;

    # 隐藏版本号(核心配置)
    server_tokens off;

    # 其他原有配置...
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        # 其他server配置...
    }
}


  • server_tokens off;:作用是关闭响应头和错误页面中的 Nginx 版本号显示。

  • 该配置必须放在http块中(对所有虚拟主机生效),若仅需对特定虚拟主机生效,可放在对应server块中。

3. 验证配置并重启 Nginx

检查配置文件语法是否正确:

bash

nginx -t

若显示nginx: configuration file /etc/nginx/nginx.conf test is successful,则配置无误。

重启 Nginx 使配置生效:

# 系统ctl管理(如CentOS 7+/Ubuntu 16+)
systemctl restart nginx

# 源码安装或旧系统
/usr/local/nginx/sbin/nginx -s reload

三、验证是否生效

1. 检查响应头

使用curl命令查看服务器响应头:

curl -I http://你的域名或IP
  • 未配置前:Server: nginx/1.21.6(显示版本号)

  • 配置后:Server: nginx(仅显示软件名称,无版本号)

2. 检查错误页面

故意访问一个不存在的页面(如http://你的域名/404test),查看错误页面(如 404 页面)底部的 Nginx 信息:

  • 未配置前:可能显示nginx/1.21.6

  • 配置后:仅显示nginx(无版本号)

四、进阶:修改Server头字段(可选)

如果希望完全隐藏nginx标识(如改为WebServer),需要重新编译 Nginx 源码,修改src/http/ngx_http_header_filter_module.c中的默认值:

# 原定义
static u_char ngx_http_server_string[] = "Server: nginx" CRLF;

# 修改为自定义名称(如WebServer)
static u_char ngx_http_server_string[] = "Server: WebServer" CRLF;

修改后重新编译安装 Nginx,即可实现Server: WebServer的响应头。