漯河市中国转运网

Nginx配置文件完全指南

2026-03-31 21:19:02 浏览次数:0
详细信息
Nginx配置文件完全指南

一、Nginx配置文件结构

1.1 配置文件位置

# 主配置文件
/etc/nginx/nginx.conf

# 配置目录
/etc/nginx/conf.d/      # 用户自定义配置
/etc/nginx/sites-available/  # 可用站点配置
/etc/nginx/sites-enabled/    # 启用的站点配置(符号链接)

# 默认配置文件示例位置
/usr/share/nginx/html/index.html

1.2 配置文件层次结构

# 全局块(影响整个Nginx服务器的配置)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;

# events块(影响Nginx服务器与用户的网络连接)
events {
    worker_connections 1024;
    use epoll;
}

# http块(最重要的配置部分)
http {
    # 通用配置
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # server块(虚拟主机配置)
    server {
        # 监听配置
        listen 80;
        server_name example.com;

        # location块(URL匹配和请求处理)
        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
    }
}

二、核心配置指令详解

2.1 全局配置

# 运行用户和组
user www-data;
pid /run/nginx.pid;

# 工作进程数(通常设为CPU核心数或auto)
worker_processes auto;

# 错误日志配置
error_log /var/log/nginx/error.log warn;
# 日志级别:debug, info, notice, warn, error, crit

# 文件描述符限制
worker_rlimit_nofile 65535;

# 加载动态模块
load_module modules/ngx_http_geoip_module.so;

2.2 Events块配置

events {
    # 每个worker的最大连接数
    worker_connections 2048;

    # 连接处理模型
    use epoll;  # Linux高效模型

    # 多连接接受处理
    multi_accept on;

    # 网络优化
    accept_mutex on;
    accept_mutex_delay 500ms;
}

2.3 HTTP块核心配置

http {
    # 基础配置
    include /etc/nginx/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" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    # 性能优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 100;

    # 限制配置
    client_max_body_size 100m;
    client_body_timeout 30s;
    client_header_timeout 30s;

    # GZIP压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml+rss text/javascript;

    # 响应头安全设置
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}

三、Server块配置详解

3.1 基本服务器配置

server {
    # 监听配置
    listen 80;
    listen [::]:80;  # IPv6
    listen 443 ssl http2;  # HTTPS配置

    # 服务器名称(支持通配符和正则)
    server_name example.com;
    server_name *.example.com;
    server_name ~^(www\.)?(?<domain>.+)$;

    # 根目录
    root /var/www/example.com;

    # 默认文件
    index index.html index.htm index.php;

    # SSL配置
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;

    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
}

3.2 多站点配置

# 主站点
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    location / {
        root /var/www/example.com;
    }
}

# 子域名站点
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://localhost:3000;
    }
}

# 默认服务器(catch-all)
server {
    listen 80 default_server;
    server_name _;
    return 444;  # 直接关闭连接
}

四、Location块配置详解

4.1 Location匹配规则

# 优先级:精确匹配(=) > 前缀匹配(^~) > 正则表达式(~) > 普通前缀匹配
server {
    # 精确匹配
    location = /login {
        # 仅匹配 /login
    }

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

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

    # 前缀匹配(如果匹配,停止搜索正则)
    location ^~ /static/ {
        # 匹配/static/开头的请求
    }

    # 普通前缀匹配
    location / {
        # 匹配所有请求
    }
}

4.2 静态文件服务

location /static/ {
    # 静态文件配置
    alias /var/www/static/;

    # 缓存配置
    expires 30d;
    add_header Cache-Control "public, immutable";

    # 安全设置
    add_header X-Content-Type-Options "nosniff";

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}

location /uploads/ {
    # 文件上传目录
    root /var/www;

    # 限制上传文件类型
    location ~* \.(php|php5|php7|phtml)$ {
        deny all;
    }
}

4.3 PHP处理配置

location ~ \.php$ {
    # 安全设置
    try_files $uri =404;

    # FastCGI配置
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    # 包含基础参数
    include fastcgi_params;

    # 超时设置
    fastcgi_read_timeout 300;
    fastcgi_connect_timeout 300;

    # 缓冲区设置
    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
}

4.4 反向代理配置

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_read_timeout 60s;
    proxy_send_timeout 60s;

    # 缓冲区
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;

    # 其他配置
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
}

# WebSocket代理
location /ws/ {
    proxy_pass http://websocket_server;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}

五、高级配置技巧

5.1 负载均衡配置

# 定义上游服务器组
upstream backend {
    # 负载均衡算法
    least_conn;  # 最少连接数
    # ip_hash;    # IP哈希
    # random;     # 随机

    # 服务器列表
    server 192.168.1.100:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.101:8080 weight=2;
    server 192.168.1.102:8080 backup;  # 备份服务器
    server 192.168.1.103:8080 down;    # 暂时停用
}

# 使用负载均衡
location / {
    proxy_pass http://backend;
}

5.2 缓存配置

# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m 
                 inactive=60m max_size=1g use_temp_path=off;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502;

        # 绕过缓存的条件
        proxy_cache_bypass $http_cache_control;
        proxy_no_cache $http_pragma $http_authorization;
    }
}

5.3 限流配置

# 限制请求速率
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        limit_req_status 429;
    }
}

# 限制并发连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;

location /download/ {
    limit_conn addr 10;  # 每个IP最多10个连接
    limit_rate 100k;     # 限速100KB/s
}

5.4 安全配置

# 禁止特定用户代理
if ($http_user_agent ~* (wget|curl|scrapy)) {
    return 403;
}

# 防止目录遍历
location ~ /\. {
    deny all;
}

# 防止SQL注入
set $block_sql_inject 0;
if ($query_string ~ "union.*select.*\(") {
    set $block_sql_inject 1;
}
if ($block_sql_inject = 1) {
    return 403;
}

# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
    return 405;
}

# 添加安全头
add_header Content-Security-Policy "default-src 'self';";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

六、性能优化配置

6.1 连接优化

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

http {
    # TCP优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 连接保持
    keepalive_timeout 75s;
    keepalive_requests 1000;

    # 缓冲区优化
    client_body_buffer_size 128k;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;

    # 输出缓冲区
    output_buffers 1 32k;
    postpone_output 1460;
}

6.2 Gzip压缩优化

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_proxied any;
gzip_types 
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;
gzip_disable "msie6";

七、调试和日志配置

7.1 日志配置

# 自定义日志格式
log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';

# 条件日志记录
map $status $loggable {
    ~^[23]  0;  # 2xx和3xx状态码不记录
    default 1;
}

access_log /var/log/nginx/access.log combined if=$loggable;
error_log /var/log/nginx/error.log warn;

# 调试日志
error_log /var/log/nginx/debug.log debug;

7.2 调试技巧

# 添加调试头
add_header X-Nginx-Cache $upstream_cache_status;
add_header X-Backend $upstream_addr;

# 调试日志
location /debug {
    # 记录详细日志
    access_log /var/log/nginx/debug.log detailed;

    # 返回调试信息
    return 200 "Host: $host\nURI: $uri\nArgs: $args\n";
}

八、实用配置模板

8.1 完整的Web服务器配置

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 1024;
    multi_accept on;
}

http {
    # 基础配置
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # SSL配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # 日志配置
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;

    # 虚拟主机
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

8.2 生产环境配置片段

# 限制请求大小
client_max_body_size 10m;
client_body_timeout 30s;
client_header_timeout 30s;

# 防止缓冲区溢出攻击
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;

# 隐藏Nginx版本号
server_tokens off;

# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|PATCH)$) {
    return 405;
}

# 防止图片盗链
location ~* \.(jpg|jpeg|png|gif|ico)$ {
    valid_referers none blocked server_names *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

九、配置检查和维护

9.1 配置检查命令

# 检查配置语法
nginx -t
# 输出:nginx: configuration file /etc/nginx/nginx.conf test is successful

# 检查特定配置文件
nginx -t -c /etc/nginx/nginx.conf

# 显示编译参数
nginx -V

# 重新加载配置(不中断服务)
nginx -s reload

# 重新打开日志文件
nginx -s reopen

# 停止服务
nginx -s stop
nginx -s quit  # 优雅停止

9.2 常用维护命令

# 查看Nginx进程
ps aux | grep nginx

# 查看监听端口
netstat -tlnp | grep nginx
ss -tlnp | grep nginx

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

# 监控访问日志
tail -f /var/log/nginx/access.log | grep -v "200"

# 压力测试
ab -n 10000 -c 100 http://localhost/

十、故障排除

10.1 常见问题解决

502 Bad Gateway

# 检查代理配置
proxy_pass http://backend;
proxy_set_header Host $host;

# 增加超时时间
proxy_connect_timeout 60s;
proxy_read_timeout 60s;

413 Request Entity Too Large

# 增加client_max_body_size
client_max_body_size 100m;

504 Gateway Timeout

# 增加超时设置
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
fastcgi_read_timeout 300s;

重定向循环

# 检查server_name配置
server_name example.com www.example.com;

# 避免重写冲突
if ($host = 'www.example.com') {
    return 301 https://example.com$request_uri;
}

总结

Nginx配置非常灵活,掌握其配置结构和工作原理是关键。建议:

使用模块化配置,将不同功能分离到不同文件 生产环境配置前一定要进行测试 启用适当的日志记录便于调试 定期更新和优化配置 使用配置文件版本控制

这份指南覆盖了Nginx配置的主要方面,但实际应用中还需要根据具体需求进行调整和优化。

相关推荐