nginx

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nginx Configuration and Optimization

Nginx配置与优化

Overview

概述

Nginx web server configuration, reverse proxy, load balancing, performance optimization and other skills.
Nginx Web服务器配置、反向代理、负载均衡、性能优化等相关技巧。

Basic Management

基础管理

Service Control

服务控制

bash
undefined
bash
undefined

Start/Stop services

启动/停止服务

systemctl start nginx systemctl stop nginx systemctl restart nginx systemctl reload nginx # Graceful reload config
systemctl start nginx systemctl stop nginx systemctl restart nginx systemctl reload nginx # 平滑重载配置

Configuration test

配置测试

nginx -t nginx -T # Test and print config
undefined
nginx -t nginx -T # 测试并打印配置
undefined

Configuration Files

配置文件

bash
undefined
bash
undefined

Main configuration file

主配置文件

/etc/nginx/nginx.conf
/etc/nginx/nginx.conf

Site configuration

站点配置

/etc/nginx/conf.d/*.conf /etc/nginx/sites-available/ /etc/nginx/sites-enabled/
/etc/nginx/conf.d/*.conf /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

Log files

日志文件

/var/log/nginx/access.log /var/log/nginx/error.log
undefined
/var/log/nginx/access.log /var/log/nginx/error.log
undefined

Basic Configuration

基础配置

Static Website

静态网站

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/html;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    # Static resource caching
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
nginx
server {
    listen 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;
        add_header Cache-Control "public, immutable";
    }
}

HTTPS Configuration

HTTPS配置

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

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;
    
    # SSL optimization
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000" always;
}
nginx
server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;
    
    # SSL优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000" always;
}

HTTP redirect to HTTPS

HTTP重定向到HTTPS

server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }
undefined
server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }
undefined

Reverse Proxy

反向代理

Basic Proxy

基础代理

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

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}
nginx
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

WebSocket Proxy

WebSocket代理

nginx
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";
    proxy_set_header Host $host;
    proxy_read_timeout 86400;
}
nginx
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";
    proxy_set_header Host $host;
    proxy_read_timeout 86400;
}

Load Balancing

负载均衡

Basic Configuration

基础配置

nginx
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 {
    listen 80;
    
    location / {
        proxy_pass http://backend;
        proxy_next_upstream error timeout http_500;
    }
}
nginx
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 {
    listen 80;
    
    location / {
        proxy_pass http://backend;
        proxy_next_upstream error timeout http_500;
    }
}

Load Balancing Strategies

负载均衡策略

nginx
undefined
nginx
undefined

Round Robin (default)

轮询(默认)

upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; }
upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; }

IP Hash (session persistence)

IP哈希(会话保持)

upstream backend { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; }
upstream backend { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; }

Least Connections

最少连接数

upstream backend { least_conn; server 192.168.1.10:8080; server 192.168.1.11:8080; }
upstream backend { least_conn; server 192.168.1.10:8080; server 192.168.1.11:8080; }

Health Check

健康检查

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

Performance Optimization

性能优化

Basic Optimization

基础优化

nginx
undefined
nginx
undefined

nginx.conf

nginx.conf

worker_processes auto; worker_rlimit_nofile 65535;
events { worker_connections 65535; use epoll; multi_accept on; }
http { # File transfer optimization sendfile on; tcp_nopush on; tcp_nodelay on;
# Timeout settings
keepalive_timeout 65;
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;

# Buffer settings
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 32k;
}
undefined
worker_processes auto; worker_rlimit_nofile 65535;
events { worker_connections 65535; use epoll; multi_accept on; }
http { # 文件传输优化 sendfile on; tcp_nopush on; tcp_nodelay on;
# 超时设置
keepalive_timeout 65;
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;

# 缓冲区设置
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 32k;
}
undefined

Gzip Compression

Gzip压缩

nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml;
nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml;

Common Scenarios

常见场景

Scenario 1: PHP-FPM Configuration

场景1:PHP-FPM配置

nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php index.html;

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

Scenario 2: Rate Limiting

场景2:请求限流

nginx
undefined
nginx
undefined

Define rate limit zone

定义限流区域

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server { location /api/ { limit_req zone=api burst=20 nodelay; proxy_pass http://backend; } }
undefined
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server { location /api/ { limit_req zone=api burst=20 nodelay; proxy_pass http://backend; } }
undefined

Scenario 3: Access Control

场景3:访问控制

nginx
location /admin {
    allow 192.168.1.0/24;
    deny all;
    
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
nginx
location /admin {
    allow 192.168.1.0/24;
    deny all;
    
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

Troubleshooting

故障排查

ProblemSolution
Configuration error
nginx -t
to test config
502 Bad GatewayCheck backend service, upstream config
504 Gateway TimeoutIncrease proxy_read_timeout
Permission issuesCheck file permissions, SELinux
Performance issuesCheck worker_connections, log analysis
问题解决方案
配置错误使用
nginx -t
测试配置
502 Bad Gateway检查后端服务、上游配置
504 Gateway Timeout增大proxy_read_timeout值
权限问题检查文件权限、SELinux设置
性能问题检查worker_connections、分析日志