插件窝 干货文章 Nginx配置文件实例分析

Nginx配置文件实例分析

Nginx 配置 Server 文件 379    来源:    2025-04-24

以下是一个详细的Nginx配置文件实例分析,包含常见配置模块和最佳实践说明:

1. 全局块(Main Context)

user www-data;                  # 运行Nginx的用户和组
worker_processes auto;          # 自动根据CPU核心数设置工作进程数
error_log /var/log/nginx/error.log warn;  # 错误日志路径及级别
pid /run/nginx.pid;             # 进程ID文件位置
events {
    worker_connections 1024;    # 每个worker进程的最大连接数
    use epoll;                  # 使用epoll高效事件模型(Linux)
    multi_accept on;            # 允许同时接受多个连接
}

2. HTTP块(HTTP Context)

http {
    include /etc/nginx/mime.types;  # 包含MIME类型定义文件
    default_type application/octet-stream;  # 默认MIME类型

    # 日志格式定义
    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;                # 优化数据包发送
    keepalive_timeout 65;         # 保持连接超时时间
    gzip on;                      # 启用Gzip压缩
    gzip_types text/plain text/css application/json;  # 压缩类型

    # 包含其他配置文件
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

3. 服务器块(Server Context)示例

示例1:静态网站

server {
    listen 80;                   # 监听80端口
    server_name example.com www.example.com;  # 域名配置

    root /var/www/html;          # 网站根目录
    index index.html index.htm;   # 默认索引文件

    location / {
        try_files $uri $uri/ =404;  # 文件查找规则
    }

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        access_log off;
    }
}

示例2:PHP应用(如WordPress)

server {
    listen 80;
    server_name blog.example.com;

    root /var/www/wordpress;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

示例3:负载均衡配置

upstream backend {
    least_conn;                  # 最少连接负载算法
    server 192.168.1.100:8000 weight=3;
    server 192.168.1.101:8000;
    server 192.168.1.102:8000 backup;  # 备用服务器
}

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

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

4. 安全增强配置

server {
    # 禁用不必要的HTTP方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # 禁止隐藏文件访问
    location ~ /\.(?!well-known) {
        deny all;
    }

    # 安全头部
    add_header X-Content-Type-Options "nosniff";
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
}

5. HTTPS配置(Let's Encrypt)

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # SSL优化配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # HTTP强制跳转HTTPS
    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }
}

关键配置说明:

  1. 性能优化

    • worker_processes auto 自动匹配CPU核心
    • gzip 压缩减少传输体积
    • sendfile 零拷贝技术提升静态文件性能
  2. 安全配置

    • 限制HTTP方法
    • 添加安全响应头
    • 禁用隐藏文件访问
  3. 常用变量

    • $remote_addr 客户端IP
    • $request_uri 完整请求URI
    • $status 响应状态码
  4. 调试技巧

    • error_log 可设置为 debug 级别
    • 使用 nginx -t 测试配置
    • tail -f /var/log/nginx/error.log 实时查看错误

建议将不同站点的配置拆分到 /etc/nginx/sites-available/ 目录下,并通过符号链接到 /etc/nginx/sites-enabled/ 保持配置整洁。