Nginx 配置文件完全指南

Nginx 的强大之处已无需多言,正由于它过于强大,配置文件里一个参数的不同就会有完全不同的行为,容易让人摸不着头脑,今天我们就来完整分析它的配置文件里面到底有什么内容~

配置文件的基础结构

主配置文件位置

Nginx的主配置文件通常位于:

  • Linux系统/etc/nginx/nginx.conf
  • macOS(通过Homebrew安装)/usr/local/etc/nginx/nginx.conf
  • Windows系统<安装目录>/conf/nginx.conf

配置文件的层级结构

Nginx配置文件采用块状结构,主要分为以下几个层级:

ini 复制代码
# 全局块
user nginx;
worker_processes auto;
 
# events 块
events {
    worker_connections 1024;
}
 
# http 块
http {
    # http 全局块
    include mime.types;
    default_type application/octet-stream;
    
    # server 块
    server {
        # server 全局块
        listen 80;
        server_name example.com;
        
        # location 块
        location / {
            root /var/www/html;
            index index.html;
        }
    }
}
AI写代码

全局块配置详解

全局块是配置文件的最外层,影响 Nginx 服务器整体运行的配置指令。

核心配置项

ini 复制代码
# 运行 Nginx 的用户和用户组
user nginx nginx;
 
# 工作进程数(通常设置为 CPU 核心数)
worker_processes auto;
 
# 错误日志路径和级别
error_log /var/log/nginx/error.log warn;
 
# 进程 PID 文件位置
pid /var/run/nginx.pid;
 
# 最大打开文件数
worker_rlimit_nofile 65535;
AI写代码

关键参数说明

  • worker_processes:建议设置为auto或 CPU 核心数,可通过grep processor /proc/cpuinfo | wc -l查看
  • error_log级别从低到高:debuginfonoticewarnerrorcrit

Events 块配置

Events 块主要影响 Nginx 服务器与用户的网络连接。

ini 复制代码
events {
    # 单个工作进程的最大连接数
    worker_connections 10240;
    
    # 使用 epoll 事件驱动模型(Linux 推荐)
    use epoll;
    
    # 尽可能多地接受连接
    multi_accept on;
}
AI写代码

性能优化建议

  • worker_connections:理论最大并发连接数 = worker_processes × worker_connections
  • Linux 系统推荐使用epoll,BSD 系统使用kqueue

HTTP 块核心配置

HTTP 块是配置的核心部分,包含了大部分 Web 服务相关的设置。

基础配置

ini 复制代码
http {
    # 引入 MIME 类型定义
    include mime.types;
    default_type application/octet-stream;
    
    # 字符集
    charset utf-8;
    
    # 日志格式定义
    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;
    
    # 高效文件传输
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    
    # 连接超时时间
    keepalive_timeout 65;
    
    # 客户端请求体大小限制
    client_max_body_size 20m;
    
    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript 
               application/json application/javascript application/xml+rss;
}
AI写代码

性能优化配置

ini 复制代码
http {
    # 隐藏 Nginx 版本号(安全)
    server_tokens off;
    
    # 文件缓存
    open_file_cache max=10000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    
    # 客户端缓冲区大小
    client_body_buffer_size 128k;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 16k;
    
    # FastCGI 缓存(用于 PHP 等)
    fastcgi_cache_path /var/cache/nginx levels=1:2 
                       keys_zone=my_cache:10m max_size=1g 
                       inactive=60m use_temp_path=off;
}
AI写代码

Server 块配置详解

Server 块定义了一个虚拟主机,一个 HTTP 块可以包含多个 Server 块。

基础虚拟主机配置

ini 复制代码
server {
    # 监听端口
    listen 80;
    listen [::]:80;  # IPv6
    
    # 服务器域名
    server_name example.com www.example.com;
    
    # 网站根目录
    root /var/www/example.com;
    
    # 默认首页
    index index.html index.htm index.php;
    
    # 访问日志(可覆盖 http 块设置)
    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log;
}
AI写代码

HTTPS 配置

ini 复制代码
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_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    
    # SSL 会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # HSTS(强制 HTTPS)
    add_header Strict-Transport-Security "max-age=31536000" always;
}
 
# HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}
AI写代码

Location 块配置详解

Location 块是 Nginx 配置中最灵活的部分,用于匹配不同的 URI 请求。

Location 匹配规则

bash 复制代码
# 精确匹配(优先级最高)
location = /exact {
    # 只匹配 /exact
}
 
# 正则匹配(区分大小写)
location ~ .php$ {
    # 匹配以.php结尾的请求
}
 
# 正则匹配(不区分大小写)
location ~* .(jpg|jpeg|png|gif)$ {
    # 匹配图片文件
}
 
# 前缀匹配(优先级高于正则)
location ^~ /static/ {
    # 匹配以/static/开头的请求
}
 
# 普通前缀匹配
location /api/ {
    # 匹配以/api/开头的请求
}
 
# 通用匹配(最低优先级)
location / {
    # 匹配所有请求
}
AI写代码

匹配优先级(从高到低):

  1. = 精确匹配
  2. ^~ 前缀匹配
  3. ~~* 正则匹配(按配置顺序)
  4. 普通前缀匹配(最长匹配原则)

常见 Location 配置示例

静态文件服务
ini 复制代码
location / {
    root /var/www/html;
    index index.html;
    try_files $uri $uri/ =404;
}
 
# 静态资源缓存
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}
AI写代码
反向代理配置
ini 复制代码
location /api/ {
    proxy_pass http://backend_server;
    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 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}
AI写代码
PHP-FPM 配置
ini 复制代码
location ~ .php$ {
    root /var/www/html;
    fastcgi_pass unix:/var/run/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}
AI写代码

负载均衡配置

Upstream 配置

ini 复制代码
# 定义后端服务器组
upstream backend {
    # 负载均衡策略:轮询(默认)
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 backup;  # 备份服务器
    
    # 健康检查
    server 192.168.1.13:8080 max_fails=3 fail_timeout=30s;
    
    # 保持连接
    keepalive 32;
}
 
server {
    location / {
        proxy_pass http://backend;
    }
}
AI写代码

负载均衡策略

ini 复制代码
# IP Hash(同一客户端固定访问同一服务器)
upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
}
 
# 最少连接
upstream backend {
    least_conn;
    server backend1.example.com;
    server backend2.example.com;
}
 
# URL Hash
upstream backend {
    hash $request_uri consistent;
    server backend1.example.com;
    server backend2.example.com;
}
AI写代码

安全配置最佳实践

防止常见攻击

bash 复制代码
# 限制请求方法
location / {
    limit_except GET POST {
        deny all;
    }
}
 
# 防止 SQL 注入和 XSS(基础防护)
if ($request_uri ~* "(union|select|insert|delete|update|drop)") {
    return 403;
}
 
# 防止目录遍历
location ~ /. {
    deny all;
}
 
# 限制文件上传大小
client_max_body_size 10m;
AI写代码

访问控制

ini 复制代码
# IP 白名单
location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}
 
# HTTP 基本认证
location /secure/ {
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
AI写代码

限流配置

ini 复制代码
# 定义限流区域
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
 
server {
    location /api/ {
        # 限制请求频率(每秒 1 个请求,突发最多 5 个)
        limit_req zone=one burst=5 nodelay;
        
        # 限制并发连接数
        limit_conn addr 10;
    }
}
AI写代码

实战配置案例

完整的 WordPress 网站配置

ini 复制代码
server {
    listen 80;
    server_name myblog.com www.myblog.com;
    root /var/www/wordpress;
    index index.php index.html;
    
    access_log /var/log/nginx/myblog.access.log;
    error_log /var/log/nginx/myblog.error.log;
    
    # WordPress固定链接
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    
    # PHP处理
    location ~ .php$ {
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    # 静态资源缓存
    location ~* .(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 禁止访问敏感文件
    location ~ /.(ht|git) {
        deny all;
    }
    
    # 禁止访问 wp-config.php
    location = /wp-config.php {
        deny all;
    }
}
AI写代码

前后端分离的单页应用(SPA)配置

ini 复制代码
server {
    listen 80;
    server_name app.example.com;
    root /var/www/vue-app/dist;
    
    # SPA路由支持
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # API反向代理
    location /api/ {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    
    # WebSocket支持
    location /ws/ {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
AI写代码

配置文件管理与调试

配置文件模块化

建议将配置拆分为多个文件:

bash 复制代码
# 主配置文件 nginx.conf
http {
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
AI写代码

推荐的目录结构

csharp 复制代码
/etc/nginx/
├── nginx.conf              # 主配置文件
├── mime.types              # MIME 类型
├── conf.d/                 # 通用配置
│   ├── security.conf       # 安全配置
│   ├── ssl.conf            # SSL 通用配置
│   ├── gzip.conf           # 压缩配置
│   └── proxy.conf          # 代理通用配置
├── sites-available/        # 站点配置(所有)
│   ├── default
│   ├── example.com.conf
│   └── api.example.com.conf
├── sites-enabled/          # 启用的站点(软链接)
│   └── example.com.conf -> ../sites-available/example.com.conf
├── snippets/               # 可复用的配置片段
│   ├── ssl-params.conf
│   ├── proxy-params.conf
│   └── fastcgi-php.conf
└── ssl/                    # SSL 证书
    ├── example.com.crt
    ├── example.com.key
    └── dhparam.pem
AI写代码

配置验证与重载

bash 复制代码
# 检查配置文件语法
nginx -t
 
# 重新加载配置(不中断服务)
nginx -s reload
 
# 停止Nginx
nginx -s stop
 
# 优雅停止(等待当前请求完成)
nginx -s quit
AI写代码

常见问题排查

bash 复制代码
# 查看错误日志
tail -f /var/log/nginx/error.log
 
# 查看访问日志
tail -f /var/log/nginx/access.log
 
# 检查Nginx进程
ps aux | grep nginx
 
# 检查端口占用
netstat -tulpn | grep :80
AI写代码

写在最后

配置关键要点:

  1. 结构清晰:使用模块化配置,便于管理和维护
  2. 安全第一:隐藏版本号、配置SSL、设置访问控制
  3. 性能优化:合理配置 worker 进程、启用 Gzip、设置缓存
  4. 日志管理:定期清理日志,使用日志切割工具
  5. 持续学习:Nginx 功能强大,需要根据实际场景不断优化

学习建议:

  • 从基础配置开始,逐步深入高级功能
  • 在测试环境充分验证后再应用到生产环境
  • 关注 Nginx 官方文档和社区最佳实践
  • 定期审查和优化配置文件

在 [Nginx 配置文件]中,以 $ 开头的变量是 Nginx 内置的预定义变量,它们在请求处理过程中会被自动赋值。理解这些变量对于编写灵活的配置至关重要。不要被它们吓倒,虽然 Nginx 没有内置命令列出所有变量,但可以参考官方文档,见相关资源部分。实践是最好的学习方式,动手试试吧!

相关推荐
清汤饺子几秒前
用了大半年 Claude Code,我总结了 16 个实用技巧
前端·javascript·后端
ん贤3 小时前
Go channel 深入解析
开发语言·后端·golang
changhong19866 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
月月玩代码8 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
xiaokangzhe9 小时前
Nginx核心功能
运维·nginx
XPoet9 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程
码事漫谈9 小时前
从“功能实现”到“深度优化”:金仓数据库连接条件下推技术的演进之路
后端
ayaya_mana9 小时前
快速安装Nginx-UI:让Nginx管理可视化的高效方案
运维·nginx·ui
码事漫谈10 小时前
数据库查询优化中的谓词下推策略与成本感知优化实践
后端
Amour恋空10 小时前
SpringBoot+Lombok+Logback实现日志
spring boot·后端·logback