LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

Nginx 配置文件完全指南

admin
2025年12月10日 1:41 本文热度 10

Nginx 的强大之处已无需多言,更多请参考Nginx:高性能 Web 服务器的王者,正由于它过于强大,配置文件里一个参数的不同就会有完全不同的行为,容易让人摸不着头脑,本期我们就来完整分析它的配置文件里面到底有什么内容~

配置文件的基础结构

主配置文件位置

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

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

配置文件的层级结构

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

# 全局块
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;
        }
    }
}

全局块配置详解

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

核心配置项

# 运行 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;

关键参数说明

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

Events 块配置

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

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

性能优化建议

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

HTTP 块核心配置

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

基础配置

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;
}

性能优化配置

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;
}

Server 块配置详解

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

基础虚拟主机配置

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;
}

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_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;
}

Location 块配置详解

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

Location 匹配规则

# 精确匹配(优先级最高)
location = /exact {
    # 只匹配 /exact
}

# 正则匹配(区分大小写)
location ~ \.php$ {
    # 匹配以.php结尾的请求
}

# 正则匹配(不区分大小写)
location ~* \.(jpg|jpeg|png|gif)$ {
    # 匹配图片文件
}

# 前缀匹配(优先级高于正则)
location ^~ /static/ {
    # 匹配以/static/开头的请求
}

# 普通前缀匹配
location /api/ {
    # 匹配以/api/开头的请求
}

# 通用匹配(最低优先级)
location / {
    # 匹配所有请求
}

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

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

常见 Location 配置示例

静态文件服务

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";
}

反向代理配置

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;
}

PHP-FPM 配置

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;
}

负载均衡配置

Upstream 配置

# 定义后端服务器组
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;
    }
}

负载均衡策略

# 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;
}

安全配置最佳实践

防止常见攻击

# 限制请求方法
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;

访问控制

# 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;
}

限流配置

# 定义限流区域
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;
    }
}

实战配置案例

完整的 WordPress 网站配置

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;
    }
}

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

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";
    }
}

配置文件管理与调试

配置文件模块化

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

# 主配置文件 nginx.conf
http {
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

推荐的目录结构

/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

配置验证与重载

# 检查配置文件语法
nginx -t

# 重新加载配置(不中断服务)

nginx -s reload

# 停止Nginx

nginx -s stop

# 优雅停止(等待当前请求完成)

nginx -s quit

常见问题排查

# 查看错误日志
tail
 -f /var/log/nginx/error.log

# 查看访问日志

tail
 -f /var/log/nginx/access.log

# 检查Nginx进程

ps aux | grep nginx

# 检查端口占用

netstat -tulpn | grep :80

写在最后

配置关键要点:

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

学习建议:

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

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


相关资源:

  • • Nginx 官网:https://nginx.org
  • • Nginx 官方文档:http://nginx.org/en/docs
  • • Nginx 内置变量:https://nginx.org/en/docs/varindex.html
  • • 开发者文档:https://nginx.org/en/docs/dev
  • • SSL 测试:https://www.ssllabs.com/ssltest


阅读原文:原文链接


该文章在 2025/12/10 18:28:20 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved