跳转至

第八章:最佳实践

配置管理

配置文件组织

/etc/nginx/
├── nginx.conf           # 主配置
├── conf.d/              # 额外配置
│   ├── ssl.conf
│   └── proxy.conf
├── sites-available/     # 可用站点
│   └── example.com.conf
├── sites-enabled/       # 启用站点
│   └── example.com.conf -> ../sites-available/example.com.conf
└── snippets/            # 配置片段
    ├── ssl-params.conf
    └── proxy-params.conf

配置片段

# snippets/proxy-params.conf
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;

# 使用
location / {
    include snippets/proxy-params.conf;
    proxy_pass http://backend:3000;
}

性能优化

# nginx.conf
worker_processes auto;
worker_rlimit_nofile 65535;

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

http {
    # 开启文件传输优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 连接优化
    keepalive_timeout 65;
    keepalive_requests 100;

    # 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    gzip_min_length 1000;

    # 缓冲
    client_body_buffer_size 16k;
    client_max_body_size 10m;
}

监控

# 状态页面
location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

小结

最佳实践要点:

  • 配置管理:文件组织、片段复用
  • 性能优化:worker、压缩、缓冲
  • 监控:状态页面

完成本教程后,你应该能够高效配置和管理 Nginx。