Nginx 配置从零到实战

Nginx 配置从零到实战

Nginx 是互联网上使用最广泛的 Web 服务器,全球超过 30% 的网站运行在 Nginx 上。

无论你是前端还是后端开发者,理解 Nginx 的核心配置都能让你在部署和排错时事半功倍。


安装

bash
# Ubuntu/Debian
apt update && apt install nginx -y

# CentOS/RHEL
yum install nginx -y

# macOS
brew install nginx

# 验证
nginx -v
nginx -t  # 测试配置是否正确

基本概念

Nginx 架构

text
Nginx
  ├── Master Process(主进程)
  │     └── 读取配置、管理工作进程
  └── Worker Processes(工作进程)
        ├── Worker 1 → 处理请求
        ├── Worker 2 → 处理请求
        └── Worker N → 处理请求

配置文件结构

nginx
# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
events {
    worker_connections 1024;
}
http {
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

静态网站

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

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

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

反向代理

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

    location / {
        proxy_pass http://localhost: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 支持
    location /ws {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

负载均衡

nginx
upstream backend {
    # 负载均衡策略
    least_conn;  # 最少连接数
    
    server 10.0.0.1:3000 weight=3;
    server 10.0.0.2:3000 weight=2;
    server 10.0.0.3:3000 backup;  # 备用服务器
}

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

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}

负载均衡策略

| 策略 | 描述 |
|------|------|
| 轮询(默认) | 按顺序分配请求 |
| weight | 按权重分配 |
| ip_hash | 同一 IP 固定到同一服务器 |
| least_conn | 分配给连接数最少的服务器 |
| least_time | 分配给响应最快的服务器 |

HTTPS 配置

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

    # 证书路径
    ssl_certificate /etc/ssl/certs/example.com.pem;
    ssl_certificate_key /etc/ssl/private/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;

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

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}

# HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

限流配置

nginx
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location /api/ {
        # 请求限流:每秒最多10个请求
        limit_req zone=api burst=20 nodelay;
        
        # 连接限流:每个IP最多10个连接
        limit_conn addr 10;
        
        proxy_pass http://backend;
    }
}

日志配置

nginx
# 自定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" $request_time';

log_format json escape=json '{'
    '"time":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"request":"$request",'
    '"status":$status,'
    '"bytes":$body_bytes_sent,'
    '"request_time":$request_time,'
    '"referer":"$http_referer",'
    '"agent":"$http_user_agent"'
'}';

server {
    access_log /var/log/nginx/access.log main;
    # 或 JSON 格式
    access_log /var/log/nginx/access.json.log json;
    
    # 错误日志级别
    error_log /var/log/nginx/error.log warn;
}

常见配置片段

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

# 禁止访问特定路径
location ~* (\.git|\.svn|vendor|node_modules) {
    deny all;
}

# 跨域配置
location /api/ {
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
    add_header Access-Control-Allow-Headers "Content-Type, Authorization";
    
    if ($request_method = OPTIONS) {
        return 204;
    }
}

# 大文件上传
client_max_body_size 100M;
proxy_read_timeout 300;
proxy_send_timeout 300;

性能优化

nginx
# nginx.conf 全局优化
worker_processes auto;
worker_rlimit_nofile 65535;

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

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    
    # 代理缓冲
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;
    
    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    gzip_min_length 1000;
    gzip_vary on;
    
    # 客户端超时
    keepalive_timeout 65;
    client_body_timeout 10;
    client_header_timeout 10;
}

常用命令

bash
nginx -t              # 测试配置文件
nginx -s reload       # 重载配置
nginx -s stop         # 停止
nginx -s quit         # 优雅停止
nginx -T              # 打印完整配置
systemctl restart nginx  # systemd 重启


Nginx 的配置看似复杂,但掌握了 server、location、proxy_pass 这三个核心概念后,大部分需求都能轻松应对。

推荐指数:⭐⭐⭐⭐⭐

官方文档:https://nginx.org/en/docs/

💬 评论区 (0)

暂无评论,快来抢沙发吧!