Skip to content

Nginx 主配置与子配置解析

结构分为:rpm 安装目录与 nginx.conf 说明conf.d 站点片段规范与示例;文中用语已统一勘误,技术含义不变。


第一部分:主配置文件与目录(原「nginx 配置文件解析」)

以 yum 安装的 nginx 为例

/etc/nginx/ 目录下文件解析

此目录下存放着控制 Nginx 启动、运行、虚拟主机等所有关键配置文件,主要可分为主配置文件、子配置目录、辅助文件三类。

shell
# 查看 /etc/nginx/ 目录下文件
ls /etc/nginx

# 结果如下:
conf.d     fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf          scgi_params          uwsgi_params          win-utf
default.d  fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.default  scgi_params.default  uwsgi_params.default

## 一、主配置文件
nginx.conf # 此为 Nginx 的全局核心配置文件,控制服务的整体运行参数,是启动 Nginx 时默认加载的配置文件
# 主要内容:包含 Nginx 进程数(worker_processes)、端口监听(listen)、用户权限(user)、日志路径(access_log/error_log)、进程 PID 文件路径(pid)等全局设置。
# 关键作用:通过 include 指令引入其他子配置文件(如虚拟主机配置),实现配置模块化管理。
http {
  include /usr/share/nginx/modules/*.conf; # nginx 默认自动导入
  include /etc/nginx/mime.types;           # nginx 默认自动导入
  include /etc/nginx/conf.d/*.conf;        # nginx 默认自动导入
  include /etc/nginx/default.d/*.conf;     # nginx 默认自动导入
}

## 二、核心子配置目录(子配置目录用于拆分不同功能的配置,避免主配置文件过于臃肿)
conf.d/ # 存放虚拟主机配置文件,每个网站 / 应用的独立配置在此定义,文件需以 .conf 结尾。
# 该目录下的.conf文件对应单个网站或应用的配置,以 example.conf 为例:
# server块:定义一个虚拟主机,通过listen 80;指定端口,server_name example.com;指定域名。
# location块:匹配 URL 路径并设置规则,如location / { root /usr/share/nginx/html; index index.html; }(指定网站根目录和默认首页)。

/etc/nginx/default.d/ # 存放默认配置片段,可被主配置或虚拟主机配置引用,用于统一复用配置
# 当访问.html文件时,Nginx 会返回Content-Type: text/html,让浏览器正确解析为网页。
# 当访问.js文件时,返回Content-Type: application/javascript,确保浏览器按脚本执行。

## 三、辅助配置文件
mime.types # 定义MIME 类型映射,告诉 Nginx 如何识别不同后缀的文件(如.html、.css)并返回正确的 HTTP 头
# 无需手动修改,主要作用是关联文件后缀与 HTTP 响应头的Content-Type,比如:

fastcgi_params / fastcgi.conf # 提供 FastCGI 相关的参数配置,用于 Nginx 与 PHP 等动态语言服务(如 PHP-FPM)的通信,传递请求头、环境变量等信息。

配置文件加载顺序

  1. 优先加载主配置文件 /etc/nginx/nginx.conf。
  2. 主配置文件中通过 include /etc/nginx/conf.d/*.conf; 加载 conf.d/ 下所有 .conf 文件。
  3. 同时通过 include /etc/nginx/sites-enabled/*; 加载 sites-enabled/ 下所有已启用的虚拟主机配置。
  4. 配置片段(snippets/)和 MIME 类型(mime.types)则在需要时,通过对应 include 指令按需加载。

解析 nginx.conf 配置文件

shell
user  nobody; # 配置哪些用户和用户组可以操作 nginx 服务器,默认:nobody,所有用户都可操作,如果为 user root root; 那么只有 root 用户和用户组可以操作 nginx 服务器
worker_processes  1; # 允许生成的进程数,默认为1,此数量越大处理并发请求越多,但数量过多会影响服务器性能,一般最大为CPU核数,设置为 auto 代表 CPU 核数
error_log  logs/error.log  notice; # 指定错误日志的存储路径和级别,级别(debug|info|notice|warn|error|crit|alert|emerg),这个代码块的位置可以放入全局块,http块,server块中,看情况而定
pid /var/run/nginx.pid;  # nginx 服务进程运行时的 pid 文件的存放地址,nginx服务关闭时此文件消失

# 事件配置:指定单个进程的最大连接数、设置网络连接序列化、是否允许同时接受多个网络连接
events {
    worker_connections  1024; # 每个工作进程的最大连接数
    accept_mutex on;   # 设置网络连接序列化,防止惊群现象发生,默认为on
    multi_accept off;  # 允许同时接受多个网络连接,on/off
    use epoll; # 启用 epoll 事件模型(Linux 系统推荐,提升性能),模型(select|poll|kqueue|epoll|resig|/dev/poll|eventport),默认:select
}

# HTTP 核心配置:内部可嵌套多个server,配置代理,缓存,日志定义、文件引入、连接超时,单连接请求数等
http {
    include       /etc/nginx/mime.types; # 引入 MIME 类型定义(映射文件扩展名与响应类型)
    default_type  application/octet-stream;  # 默认文件类型,默认为text/plain,application/octet-stream 是 MIME 中的一种类型

    # 自定义 nginx 服务日志格式(main 为默认格式)
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log main; # 配置 nginx 服务日志存放路径和格式化方式(使用 main 格式),值为 off 代表取消服务日志
    
    # 性能优化配置
    sendfile on;              # 启用零拷贝发送文件,默认为off,可以在http块,server块,location块中设置。
    sendfile_max_chunk 100k;  # 每个进程每次调用传输数量不能大于设定的值,默认为0,无上限。
    tcp_nopush on;            # 与 sendfile 配合使用,是一种非常实用的TCP/IP协议选项,可以提高网络传输效率,减少缓冲操作对系统性能的影响
    tcp_nodelay on;           # 减少网络延迟(适用于实时性要求高的场景)
    keepalive_timeout 65;     # 长连接超时时间(秒),默认为75s,可以在http,server,location块中设置。值为 0 会禁用keep-alive
    types_hash_max_size 2048; # 类型哈希表大小(提升查找效率)

    # 开启 gzip 压缩(减少传输数据量,提升网站访问速度),对 HTML、CSS、JS 类文件进行压缩去除文件的空格和换行符以达到压缩目的。对图片、视频等二进制文件无效
    gzip  on;                # 开启
    gzip_vary on;            # 告诉客户端支持 gzip 压缩
    gzip_proxied any;        # 对代理请求也启用压缩
    gzip_comp_level 6;       # 压缩级别(1-9,越高压缩率越高但耗 CPU)
    gzip_buffers 16 8k;      # 压缩缓冲区大小
    gzip_http_version 1.1;   # 支持的 HTTP 版本
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; # 可压缩的文件格式
    
     # 引入虚拟主机配置(推荐将站点配置拆分到 conf.d 目录)
    include /usr/share/nginx/modules/*.conf; # nginx 默认自动导入
    include /etc/nginx/mime.types;           # nginx 默认自动导入
    include /etc/nginx/conf.d/*.conf;        # nginx 默认自动导入
    include /etc/nginx/default.d/*.conf;     # nginx 默认自动导入

    # 配置服务连接池,常用于服务备份和负载均衡配置
    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup; # 热备:当 127.0.0.1:7878 服务阻塞时,调用 192.168.10.121:3333 服务
    }
    
    # 请求异常跳转页面
    error_page   500 502 503 504  /50x.html; 

    # 默认站点/虚拟主机 配置(可多个):默认服务器(未匹配 include 导入的主机时生效), 配置虚拟主机的相关参数、配置反向代理、动静分离、https 配置等 -----------------------------
    server {
        listen 80 default_server; # ipv4 监听端口
        listen [::]:80 default_server; # ipv6 监听端口,生产环境中,为了让网站同时对 IPv4 和 IPv6 用户可用,可配置两个端口监听

        server_name _; # 服务器名称(可填写域名,默认不限制),值为_,代表匹配所有未被其他 server 匹配的请求,值为 localhost 代表本机
        charset utf-8; # 编码格式,默认 charset koi8-r; 俄语编码
        
        access_log  logs/host.access.log  main; # 本站点 服务日志的存储路径
        
        # 网站根目录匹配规则
        location / {
            root /usr/share/nginx/html; # 网站根目录,当用户访问 http://xxx.com/path/file.html 时,Nginx 会实际查找 /usr/share/nginx/html/path/file.html 文件
            index index.html index.htm; # 默认索引文件,访问根目录时,Nginx 会先找 index.html,如果不存在则找 index.htm,如果都不存在则可能返回 403 错误(取决于是否允许目录浏览)
        }
        
        # 后端服务反向代理
        location /api/ {   
           proxy_pass  http://mysvr;  # 后端服务地址,值为:域名、ip、upstream 连接池
           
           proxy_set_header Host $host; # 将客户端请求的 Host 头(即访问的域名或 IP)传递给后端服务器。
           proxy_set_header X-Real-IP $remote_addr; # 将客户端的真实 IP 地址传递给后端服务器
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 记录请求经过的所有代理服务器的 IP 链,包括客户端原始 IP
           proxy_set_header X-Forwarded-Proto $scheme; # 将客户端请求的协议(HTTP 或 HTTPS)传递给后端服务器
           
           deny 172.18.5.5;  # 访问控制,限制特定 IP 访问,比如:拒绝 172.18.5.5 访问,值为 all 代表所有
           allow 172.18.5.0/24; # 访问控制,限制特定 IP 访问,比如:仅允许172.18.5.0/24网段内的 ip 访问,拒绝本地和其他IP,值为 all 代表所有
        } 
        
        # 静态资源缓存配置(图片、CSS、JS 等)
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 30d;           # 缓存 30 天
            add_header Cache-Control "public, max-age=2592000";
        }

        error_page 404 /404.html; # 本站点 404 页面配置
        error_page 500 502 503 504 /50x.html; # 本站点 50x 错误页面配置
        
        # 精确匹配:当 url 匹配 /50x.html 时,立即访问 usr/share/nginx/html/50x.html
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
    
    # SSL 配置(https 协议)
     server {
         listen 443 ssl;
         server_name example.com www.example.com;

         # SSL 证书路径
         ssl_certificate /etc/nginx/ssl/example.com.crt;
         ssl_certificate_key /etc/nginx/ssl/example.com.key;

         # SSL 优化配置
         ssl_protocols TLSv1.2 TLSv1.3;  # 仅支持安全的 TLS 版本
         ssl_prefer_server_ciphers on;
         ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
         ssl_session_cache shared:SSL:10m;  # SSL 会话缓存
         ssl_session_timeout 10m;

         # 网站根目录
         root /var/www/example.com;
         index index.html;
     } 
}

location 匹配路由规则

shell
# 基础语法
location [修饰符] 模式 { ... }

# 修饰符:决定匹配方式和优先级(无修饰符时为普通匹配)。
=    # 精确匹配,必须完全一致。优先级:最高(一旦匹配,立即停止后续匹配)
^~   # 前缀匹配(优先于正则),优先级:高于正则匹配,低于精确匹配
~    # 区分大小写的正则匹配。优先级:高于普通前缀匹配,低于 = 和 ^~
~*   # 不区分大小写的正则匹配。优先级:高于普通前缀匹配,低于 = 和 ^~
无修饰符 # 匹配以模式为前缀的 URI,多个普通前缀匹配时,最长的匹配结果生效,优先级:最低(仅在前面的规则都不匹配时生效)
优先级顺序(一旦匹配,不再更改):精确 > 前缀 > 正则 > 无修饰符

# 模式
URI 匹配的字符串或正则表达式。

# 常见示例
location = / {
    # 1. 精确匹配 /(首页)
}
location ^~ /static/ {
    # 2. 前缀匹配 /static/,优先级高于正则
}
location ~* \.(jpg|png)$ {
    # 3. 正则匹配图片后缀(不区分大小写)
}
location /user {
    # 4. 无修饰符,普通前缀匹配 /user 开头的 URI(如 /user/123)
}
location / {
    # 5. 兜底,匹配所有未被上述规则匹配的 URI(最长前缀为 /)
}

location 与 root 的关系 (很关键)

  1. 二者原理
shell
# 原理
location 的作用:只是匹配路由规则,匹配了就执行内部逻辑,仅此而已
root 的作用:把请求的 url 的协议域名端口(不包括后面的斜杠),替换成 root 的值,最终结果作为实际访问的服务器上资源地址

# 示例
location /app {
    root /usr/share/nginx; 
}
# 当 url 为 http://example.com/app/index.html 时
# 第一步:匹配到 /app,那么符合当前规则,所以执行内部逻辑
# 第二步:把 http://example.com 替换成 /usr/share/nginx
# 最终结果为:/usr/share/nginx/app/index.html

# 注意
# location 是否以 / 结尾影响不大,只要保证能匹配上即可
# root 的值是否以 / 结尾也影响不大,Nginx 会自动处理路径拼接,不会导致错误。
# 推荐 都不以 / 结尾
  1. root 的值,以 “/” 开头是绝对路径,非 “/” 开头是相对路径
shell
# 以 / 开头的绝对路径(推荐)
location /app {
    root /usr/share/nginx; 
    # 访问 http://example.com/app/index.html 时,Nginx实际查找的文件路径是:/usr/share/nginx/app/index.html
}

# 不以 / 开头的相对路径,相对于当前 nginx.conf 所在目录,即:/etc/nginx/
location /app {
    root html/test; 
    # 访问 http://example.com/app/index.html 时,Nginx实际查找的文件路径是:/etc/nginx/html/test/app/index.html
}

反向代理 proxy_pass(跟关键)

shell
server {
    listen 80;
    server_name your-domain.com;

    # API 接口:代理到 3000 端口的后端服务
    location /api {
        proxy_pass http://127.0.0.1:3000;  # 注意:目标地址后是否加 / 会影响路径拼接
        # 若 proxy_pass 目标地址以 / 结尾,(如 http://127.0.0.1:3000/),则请求 /api/user 会被代理为 http://127.0.0.1:3000/user
        # 若 proxy_pass 目标地址不以 / 结尾,则代理为 http://127.0.0.1:3000/api/user
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

注意事项

  1. 任何配置变更后,需执行 nginx -t 测试配置语法是否正确,无误后再用 systemctl reload nginx 重启服务。
  2. 直接在 conf.d/ 目录下新建 域名.conf 文件,无需修改主配置,更便于管理
  3. 修改重要文件(如nginx.conf)前,建议先备份
  4. 路径(如网站根目录、日志路径、证书路径)需根据实际环境修改,并确保 Nginx 进程有访问权限
  5. 生产环境中建议启用 HTTPS,并配置合适的缓存、超时和安全策略。

第二部分:conf.d 子配置(原「nginx 子配置文件解析」)

在 Nginx 中,/etc/nginx/conf.d/ 目录通常用于存放站点的配置文件(以 .conf 结尾), 这些文件会被主配置文件(/etc/nginx/nginx.conf)通过 include /etc/nginx/conf.d/*.conf; 语句引入。

子配置文件规范

shell
# 文件命名规范
域名.conf # 比如:example.com.conf

# 内容规范
每个 .conf 文件通常对应一个站点或服务,便于管理。即:只定义一个 server 块儿

基础站点配置

静态网站,监听 80 端口

shell
# 定义站点配置
server {
    # 监听端口(HTTP 默认 80)
    listen 80;
    # 绑定的域名(可多个,用空格分隔)
    server_name example.com www.example.com;

    # 网站根目录(静态文件存放路径)
    root /var/www/example.com;
    # 默认索引文件
    index index.html index.htm index.php;

    # 访问日志和错误日志路径
    access_log /var/log/nginx/example.com_access.log;
    error_log /var/log/nginx/example.com_error.log;

    # 静态文件缓存配置(可选)
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;  # 缓存 30 天
        add_header Cache-Control "public, max-age=2592000";
    }

    # 禁止访问隐藏文件(如 .git、.htaccess 等)
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}

HTTPS 站点配置

用于部署启用 SSL/TLS 的 HTTPS 站点(需提前准备 SSL 证书)

shell
server {
    # 监听 HTTPS 端口(默认 443),并指定 SSL 协议
    listen 443 ssl http2;
    server_name example.com www.example.com;

    # SSL 证书路径(替换为实际证书路径)
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # SSL 配置优化(增强安全性)
    ssl_protocols TLSv1.2 TLSv1.3;  # 仅支持安全的 TLS 版本
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;  # 启用 SSL 会话缓存
    ssl_session_timeout 10m;

    # 网站根目录和索引文件
    root /var/www/example.com;
    index index.html index.htm;

    # 日志配置
    access_log /var/log/nginx/example.com_ssl_access.log;
    error_log /var/log/nginx/example.com_ssl_error.log;

    # 强制 HTTP 跳转 HTTPS(可选,配合下方 80 端口配置)
    # 可单独写一个 80 端口的 server 块实现跳转
}

# 可选:HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;  # 永久重定向到 HTTPS
}

反向代理配置

将请求代理到后端服务

shell
server {
    listen 80;
    server_name api.example.com;

    # 访问日志
    access_log /var/log/nginx/api_proxy_access.log;
    error_log /var/log/nginx/api_proxy_error.log;

    # 反向代理到后端服务(例如:本地 3000 端口的 Node.js 应用)
    location / {
        # 后端服务地址
        proxy_pass http://127.0.0.1:3000;
        
        # 传递客户端信息到后端
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # 超时配置
        proxy_connect_timeout 30s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}