CodeL
以前端为翼,以 AI 为脑,向全栈而行
2026-03-31

Nginx 配置文件完整教程

Nginx 配置文件完整教程 从零到精通,覆盖静态网站、HTTPS、反向代理、负载均衡等核心场景。 目录 一、配置文件位置 二、整体结构 三、全局块配置 四、events 块配置 五、http 块配置 六、server...

Nginx 配置文件完整教程 #

从零到精通,覆盖静态网站、HTTPS、反向代理、负载均衡等核心场景。


目录 #


一、配置文件位置 #

系统 默认路径
CentOS/RHEL /etc/nginx/nginx.conf
Ubuntu/Debian /etc/nginx/nginx.conf
Windows 解压目录/conf/nginx.conf
自定义安装 /usr/local/nginx/conf/nginx.conf

查找命令

find / -name nginx.conf 2>/dev/null
nginx -t  # 显示当前使用的配置文件路径

二、整体结构 #

# 全局块 - 影响 Nginx 整体运行
worker_processes auto;
 
# events 块 - 网络连接配置
events {
    worker_connections 10240;
}
 
# http 块 - HTTP 服务核心
http {
    # http 全局配置
    
    server {
        # 虚拟主机(一个 server = 一个网站)
        
        location {
            # 路由匹配
        }
    }
}

嵌套规则:子块继承父块配置,可覆盖。


三、全局块配置 #

配置项 说明 推荐值
user 运行用户 user nginx;(Linux)
worker_processes 工作进程数 auto(自动匹配 CPU 核心)
error_log 错误日志 /var/log/nginx/error.log warn;
pid 进程 ID 文件 /var/run/nginx.pid;
worker_rlimit_nofile 最大打开文件数 65535;

示例

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_rlimit_nofile 65535;

四、events 块配置 #

配置项 说明 推荐值
use 事件模型 epoll(Linux 最佳)
worker_connections 单进程最大连接数 10240
multi_accept 批量接受连接 on

最大并发 = worker_processes × worker_connections

示例

events {
    use epoll;
    worker_connections 10240;
    multi_accept on;
}

五、http 块配置 #

5.1 基础配置 #

http {
    # MIME 类型
    include       mime.types;
    default_type  application/octet-stream;
    
    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] '
                     '"$request" $status $body_bytes_sent '
                     '"$http_referer" "$http_user_agent"';
    access_log /var/log/nginx/access.log main;
    
    # 高效传输
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    
    # 连接保持
    keepalive_timeout 65;
    
    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    gzip_min_length 1000;
}

5.2 包含子配置 #

http {
    # 包含虚拟主机配置(推荐方式)
    include /etc/nginx/conf.d/*.conf;
}

六、server 块配置 #

6.1 基本结构 #

server {
    listen 80;                    # 监听端口
    server_name example.com;      # 绑定域名
    root /var/www/html;           # 网站根目录
    index index.html index.htm;   # 默认首页
    
    access_log /var/log/nginx/example.access.log;
    error_log  /var/log/nginx/example.error.log;
}

6.2 多域名配置 #

server {
    listen 80;
    server_name example.com www.example.com;
    # ...
}

6.3 多网站配置 #

# 网站 A
server {
    listen 80;
    server_name www.example.com;
    root /var/www/example;
}
 
# 网站 B
server {
    listen 80;
    server_name blog.example.com;
    root /var/www/blog;
}

七、location 块配置 #

7.1 匹配规则(优先级从高到低) #

语法 说明 示例
= 精确匹配 location = /index.html
^~ 前缀匹配(优先正则) location ^~ /static
~ 正则匹配(区分大小写) location ~ \.php$
~* 正则匹配(不区分大小写) location ~* \.jpg$
无符号 普通前缀匹配(优先级最低) location /api

7.2 常用配置项 #

配置项 说明
root 根目录(路径拼接)
alias 别名(路径替换)
proxy_pass 反向代理
try_files 尝试查找文件
expires 缓存时间
deny/allow IP 访问控制

7.3 root vs alias #

# root:路径拼接
location /static {
    root /var/www;  # /static/1.jpg → /var/www/static/1.jpg
}
 
# alias:路径替换
location /static {
    alias /var/www/static/;  # /static/1.jpg → /var/www/static/1.jpg
}

7.4 完整示例 #

server {
    listen 80;
    server_name example.com;
    root /var/www;
    
    # 精确匹配首页
    location = / {
        index index.html;
    }
    
    # 静态资源缓存
    location ^~ /static/ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 反向代理 API
    location ~ ^/api {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
    
    # SPA 单页应用
    location / {
        try_files $uri $uri/ /index.html;
    }
}

八、实战场景配置 #

场景 1:静态网站 #

server {
    listen 80;
    server_name blog.example.com;
    root /var/www/blog;
    index index.html;
    
    # 静态资源缓存
    location ^~ /assets/ {
        expires 30d;
    }
    
    # 禁止隐藏文件
    location ~ /\. {
        deny all;
    }
}

场景 2:HTTP → HTTPS #

# HTTP 跳转
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}
 
# HTTPS 服务
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL 证书
    ssl_certificate     /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    # SSL 配置
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    
    # HSTS(可选,增强安全)
    add_header Strict-Transport-Security "max-age=31536000" always;
    
    root /var/www;
    index index.html;
}

场景 3:反向代理(前后端分离) #

server {
    listen 80;
    server_name example.com;
    
    root /var/www/frontend;
    
    # 前端 SPA
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # API 反向代理
    location ~ ^/api {
        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;
        
        # WebSocket 支持
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

场景 4:负载均衡 #

# 定义后端集群
upstream backend {
    least_conn;  # 最少连接优先
    server 127.0.0.1:3000 weight=5;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002 backup;  # 备用服务器
    
    # 健康检查(需第三方模块)
    # keepalive 32;
}
 
server {
    listen 80;
    
    location ~ ^/api {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}

负载均衡算法

算法 说明
轮询(默认) 依次分配
weight 权重分配
least_conn 最少连接优先
ip_hash 同 IP 固定服务器

场景 5:限流防攻击 #

# 定义限流规则
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
 
server {
    listen 80;
    
    location ~ ^/api {
        limit_req zone=api_limit burst=20 nodelay;
        proxy_pass http://127.0.0.1:3000;
    }
    
    # 禁止特定 IP
    location /admin {
        allow 192.168.1.0/24;
        deny all;
    }
}

场景 6:文件上传代理 #

server {
    listen 80;
    
    location ~ ^/upload {
        proxy_pass http://127.0.0.1:3000;
        
        # 大文件上传配置
        client_max_body_size 100m;
        proxy_connect_timeout 300;
        proxy_send_timeout    300;
        proxy_read_timeout    300;
    }
}

九、常见问题排查 #

9.1 配置检查 #

nginx -t  # 检查语法,显示错误位置

9.2 常见错误 #

错误信息 原因 解决
missing ';' 漏写分号 补上分号
unknown directive 配置项拼写错误 检查拼写
permission denied 权限不足 chmod 755 目录权限
Address already in use 端口被占用 `netstat -tulnp

9.3 管理命令 #

nginx              # 启动
nginx -s reload    # 重载配置(不中断服务)
nginx -s stop      # 快速停止
nginx -s quit      # 优雅停止(处理完请求再停)
nginx -t           # 检查配置
nginx -v           # 查看版本

9.4 日志位置 #

# 查看错误日志
tail -f /var/log/nginx/error.log
 
# 查看访问日志
tail -f /var/log/nginx/access.log
 
# 实时监控状态
tail -f /var/log/nginx/access.log | grep " 500 "

十、总结速记 #

类型 核心要点
结构 全局 → events → http → server → location
高频配置 listenserver_namerootproxy_passtry_files
实战场景 静态网站、HTTPS、反向代理、负载均衡、限流
必做操作 改配置后 nginx -tnginx -s reload

附录:Nginx 变量速查 #

变量 说明
$remote_addr 客户端 IP
$remote_user 认证用户名
$time_local 访问时间
$request 请求方法和路径
$status 状态码
$body_bytes_sent 响应体大小
$http_referer 来源页面
$http_user_agent 浏览器信息
$host 主机名
$uri 当前 URI

最后更新:2026-03-28