Nginx配置最佳实践指南

深入理解Nginx配置,优化Web服务器性能

Nginx配置指南

本文将详细介绍Nginx的配置方法和最佳实践,帮助你优化Web服务器性能。

基础配置

  1. 主配置文件
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

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;
    types_hash_max_size 2048;
    
    include /etc/nginx/conf.d/*.conf;
}
  1. 虚拟主机配置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# default.conf
server {
    listen 80;
    server_name example.com;
    root /usr/share/nginx/html;
    
    location / {
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
    
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

SSL配置

  1. HTTPS设置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
server {
    listen 443 ssl;
    server_name example.com;
    
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
}
  1. HTTP/2支持
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL配置同上
    
    location / {
        http2_push_preload on;
    }
}

负载均衡

  1. 上游服务器配置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
upstream backend {
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 weight=1 backup;
    
    keepalive 32;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
  1. 健康检查
1
2
3
4
5
6
7
8
upstream backend {
    server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
    
    check interval=3000 rise=2 fall=5 timeout=1000 type=http;
    check_http_send "HEAD / HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
}

缓存配置

  1. 静态文件缓存
1
2
3
4
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}
  1. 代理缓存
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
    location / {
        proxy_cache my_cache;
        proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
        proxy_cache_valid 200 60m;
        proxy_cache_key $scheme$request_method$host$request_uri;
    }
}

安全配置

  1. 基本安全头
1
2
3
4
5
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
  1. DDoS防护
1
2
3
4
5
6
7
8
9
# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 100;

# 限制请求率
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
location / {
    limit_req zone=one burst=5 nodelay;
}

性能优化

  1. Gzip压缩
1
2
3
4
5
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
  1. 文件读取优化
1
2
3
4
5
6
7
location /downloads/ {
    sendfile on;
    tcp_nopush on;
    directio 512;
    aio on;
    output_buffers 1 128k;
}

日志配置

  1. 访问日志
1
2
3
4
5
6
log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    '$request_time $upstream_response_time';

access_log /var/log/nginx/detailed.log detailed buffer=32k flush=5s;
  1. 错误日志
1
error_log /var/log/nginx/error.log warn;

最佳实践

  1. 性能建议

    • 启用缓存
    • 优化文件读取
    • 合理配置工作进程
  2. 安全建议

    • 及时更新版本
    • 配置安全头
    • 限制请求频率

掌握这些Nginx配置技巧,将帮助你构建高性能、安全的Web服务器。

使用绝夜之城强力驱动