Skip to content

Nginx配置

1. 概述

Nginx 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。在梵医云系统中,Nginx 主要用作反向代理、负载均衡、静态资源服务器和 SSL 终端。本文档介绍如何配置和管理 Nginx。

2. Nginx 基础知识

2.1 什么是 Nginx

Nginx 是一个轻量级的 Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个 BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上 Nginx 的并发能力确实在同类型的网页服务器中表现较好。

2.2 Nginx 特性

  • 高性能:处理静态文件、索引文件以及自动索引
  • 反向代理:无缓存的反向代理加速
  • 负载均衡:支持简单的负载均衡和容错
  • FastCGI:支持 FastCGI、uWSGI、SCGI、PHPCGI
  • SSL/TLS:支持 SSL 和 TLS SNI
  • HTTP/2:支持 HTTP/2 协议
  • 模块化:支持第三方模块扩展

2.3 Nginx 架构

Nginx 采用事件驱动、异步非阻塞的处理方式,具有以下特点:

  • 主进程(Master Process):负责读取配置、管理工作进程
  • 工作进程(Worker Process):处理实际的请求
  • 事件驱动:使用 epoll/kqueue 等高效事件模型

3. 安装 Nginx

3.1 CentOS 安装 Nginx

bash
# 添加 EPEL 仓库
sudo yum install -y epel-release

# 安装 Nginx
sudo yum install -y nginx

# 启动 Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

3.2 Ubuntu 安装 Nginx

bash
# 更新软件包列表
sudo apt update

# 安装 Nginx
sudo apt install -y nginx

# 启动 Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

3.3 源码安装 Nginx

bash
# 安装依赖
sudo yum install -y gcc pcre-devel zlib-devel openssl-devel

# 下载 Nginx
cd /usr/local/src
wget http://nginx.org/download/nginx-1.24.0.tar.gz

# 解压
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 配置
./configure --prefix=/usr/local/nginx \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_realip_module \
  --with-http_gzip_static_module \
  --with-http_stub_status_module

# 编译安装
make && make install

# 启动 Nginx
/usr/local/nginx/sbin/nginx

3.4 Docker 安装 Nginx

bash
# 拉取 Nginx 镜像
docker pull nginx:alpine

# 运行 Nginx 容器
docker run -d \
  --name nginx \
  -p 80:80 \
  -p 443:443 \
  -v /data/nginx/conf:/etc/nginx/conf.d \
  -v /data/nginx/html:/usr/share/nginx/html \
  -v /data/nginx/logs:/var/log/nginx \
  --restart=always \
  nginx:alpine

4. Nginx 配置文件结构

4.1 配置文件位置

/etc/nginx/
├── nginx.conf              # 主配置文件
├── conf.d/                # 额外配置文件目录
│   ├── default.conf        # 默认站点配置
│   ├── fanyi.conf        # 梵医云站点配置
│   └── ...
├── sites-available/        # 可用站点配置
├── sites-enabled/         # 启用站点配置
├── ssl/                  # SSL 证书目录
└── logs/                 # 日志目录
    ├── access.log        # 访问日志
    └── error.log        # 错误日志

4.2 主配置文件

编辑 /etc/nginx/nginx.conf

nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

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

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;
    client_max_body_size 100M;

    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript 
               application/json application/javascript application/xml+rss 
               application/rss+xml font/truetype font/opentype 
               application/vnd.ms-fontobject image/svg+xml;

    # 包含站点配置
    include /etc/nginx/conf.d/*.conf;
}

5. 基础配置

5.1 静态网站配置

编辑 /etc/nginx/conf.d/static.conf

nginx
server {
    listen 80;
    server_name static.fanyi.example.com;

    root /var/www/static;
    index index.html index.htm;

    # 字符集
    charset utf-8;

    # 访问日志
    access_log /var/log/nginx/static_access.log;
    error_log /var/log/nginx/static_error.log;

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

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

5.2 反向代理配置

编辑 /etc/nginx/conf.d/fanyi-gateway.conf

nginx
server {
    listen 80;
    server_name fanyi.example.com www.fanyi.example.com;

    # 访问日志
    access_log /var/log/nginx/fanyi_access.log;
    error_log /var/log/nginx/fanyi_error.log;

    # 反向代理配置
    location / {
        proxy_pass http://127.0.0.1:48080;
        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_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # 超时配置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 缓冲配置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
    }

    # WebSocket 支持
    location /ws {
        proxy_pass http://127.0.0.1:48080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}

5.3 HTTPS 配置

编辑 /etc/nginx/conf.d/fanyi-https.conf

nginx
# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name fanyi.example.com www.fanyi.example.com;
    return 301 https://$server_name$request_uri;
}

# HTTPS 配置
server {
    listen 443 ssl http2;
    server_name fanyi.example.com www.fanyi.example.com;

    # 证书配置
    ssl_certificate /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;

    # SSL 协议配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;

    # SSL 会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/nginx/ssl/chain.pem;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

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

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # 访问日志
    access_log /var/log/nginx/fanyi_access.log;
    error_log /var/log/nginx/fanyi_error.log;

    # 反向代理配置
    location / {
        proxy_pass http://127.0.0.1:48080;
        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_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
    }

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

6. 负载均衡配置

6.1 轮询负载均衡

编辑 /etc/nginx/conf.d/load-balance.conf

nginx
upstream fanyi_backend {
    server 192.168.1.10:48080;
    server 192.168.1.11:48080;
    server 192.168.1.12:48080;
}

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

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

6.2 加权轮询负载均衡

nginx
upstream fanyi_backend {
    server 192.168.1.10:48080 weight=3;
    server 192.168.1.11:48080 weight=2;
    server 192.168.1.12:48080 weight=1;
}

6.3 IP 哈希负载均衡

nginx
upstream fanyi_backend {
    ip_hash;
    server 192.168.1.10:48080;
    server 192.168.1.11:48080;
    server 192.168.1.12:48080;
}

6.4 最少连接负载均衡

nginx
upstream fanyi_backend {
    least_conn;
    server 192.168.1.10:48080;
    server 192.168.1.11:48080;
    server 192.168.1.12:48080;
}

6.5 健康检查配置

nginx
upstream fanyi_backend {
    server 192.168.1.10:48080 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:48080 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:48080 max_fails=3 fail_timeout=30s;
}

7. 梵医云系统配置

7.1 Gateway 配置

编辑 /etc/nginx/conf.d/fanyi-gateway.conf

nginx
upstream fanyi_gateway {
    server 127.0.0.1:48080;
    keepalive 32;
}

server {
    listen 80;
    server_name fanyi.example.com www.fanyi.example.com;

    # 访问日志
    access_log /var/log/nginx/fanyi_gateway_access.log;
    error_log /var/log/nginx/fanyi_gateway_error.log;

    # 反向代理配置
    location / {
        proxy_pass http://fanyi_gateway;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # 超时配置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 缓冲配置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;
    }

    # WebSocket 支持
    location /ws {
        proxy_pass http://fanyi_gateway;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}

7.2 System 模块配置

编辑 /etc/nginx/conf.d/fanyi-system.conf

nginx
upstream fanyi_system {
    server 127.0.0.1:48081;
    keepalive 32;
}

server {
    listen 80;
    server_name system.fanyi.example.com;

    # 访问日志
    access_log /var/log/nginx/fanyi_system_access.log;
    error_log /var/log/nginx/fanyi_system_error.log;

    # 反向代理配置
    location / {
        proxy_pass http://fanyi_system;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;
    }
}

7.3 Member 模块配置

编辑 /etc/nginx/conf.d/fanyi-member.conf

nginx
upstream fanyi_member {
    server 127.0.0.1:48087;
    keepalive 32;
}

server {
    listen 80;
    server_name member.fanyi.example.com;

    # 访问日志
    access_log /var/log/nginx/fanyi_member_access.log;
    error_log /var/log/nginx/fanyi_member_error.log;

    # 反向代理配置
    location / {
        proxy_pass http://fanyi_member;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;
    }
}

7.4 Trade 模块配置

编辑 /etc/nginx/conf.d/fanyi-trade.conf

nginx
upstream fanyi_trade {
    server 127.0.0.1:48090;
    keepalive 32;
}

server {
    listen 80;
    server_name trade.fanyi.example.com;

    # 访问日志
    access_log /var/log/nginx/fanyi_trade_access.log;
    error_log /var/log/nginx/fanyi_trade_error.log;

    # 反向代理配置
    location / {
        proxy_pass http://fanyi_trade;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;
    }
}

8. 性能优化

8.1 工作进程配置

nginx
worker_processes auto;
worker_rlimit_nofile 65535;

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

8.2 连接优化

nginx
http {
    # 保持连接
    keepalive_timeout 65;
    keepalive_requests 100;

    # TCP 优化
    tcp_nopush on;
    tcp_nodelay on;

    # 缓冲区优化
    client_body_buffer_size 128k;
    client_max_body_size 100M;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 4k;
    output_buffers 1 32k;
    postpone_output 1460;
}

8.3 Gzip 压缩

nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript 
           application/json application/javascript application/xml+rss 
           application/rss+xml font/truetype font/opentype 
           application/vnd.ms-fontobject image/svg+xml;
gzip_disable "msie6";

8.4 缓存配置

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

server {
    location / {
        proxy_cache cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_bypass $http_upgrade;
        proxy_no_cache $http_upgrade;
        
        add_header X-Cache-Status $upstream_cache_status;
    }
}

8.5 文件描述符限制

bash
# 修改系统限制
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf

# 临时生效
ulimit -n 65535

9. 安全配置

9.1 隐藏版本号

nginx
http {
    server_tokens off;
}

9.2 限制请求方法

nginx
server {
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

9.3 防止目录遍历

nginx
server {
    location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak)$ {
        deny all;
        access_log off;
        log_not_found off;
    }
}

9.4 限制请求速率

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

server {
    # 应用限流
    limit_req zone=one burst=20 nodelay;
    
    location / {
        proxy_pass http://backend;
    }
}

9.5 IP 白名单

nginx
server {
    # 允许的 IP
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    
    # 拒绝其他 IP
    deny all;
    
    location / {
        proxy_pass http://backend;
    }
}

9.6 防止图片盗链

nginx
server {
    location ~* \.(jpg|jpeg|png|gif)$ {
        valid_referers none blocked fanyi.example.com www.fanyi.example.com;
        
        if ($invalid_referer) {
            return 403;
        }
    }
}

10. 日志管理

10.1 日志格式

nginx
http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    log_format json_combined escape=json '{'
        '"time_local":"$time_local",'
        '"remote_addr":"$remote_addr",'
        '"remote_user":"$remote_user",'
        '"request":"$request",'
        '"status": "$status",'
        '"body_bytes_sent":"$body_bytes_sent",'
        '"request_time":"$request_time",'
        '"http_referrer":"$http_referer",'
        '"http_user_agent":"$http_user_agent"'
    '}';

    access_log /var/log/nginx/access.log json_combined;
}

10.2 日志轮转

创建 /etc/logrotate.d/nginx

/var/log/nginx/*.log {
    daily
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

10.3 日志分析

使用 GoAccess 分析日志:

bash
# 安装 GoAccess
yum install -y goaccess

# 实时分析
goaccess /var/log/nginx/access.log -c -a -d -f -p /etc/goaccess.conf

# 生成 HTML 报告
goaccess /var/log/nginx/access.log -o /var/www/report.html --log-format=COMBINED

11. 监控和状态

11.1 启用状态页面

nginx
server {
    listen 8080;
    server_name localhost;
    
    # 允许访问的 IP
    allow 127.0.0.1;
    allow 192.168.1.0/24;
    deny all;
    
    location /nginx_status {
        stub_status on;
        access_log off;
    }
}

11.2 状态页面说明

访问 http://localhost:8080/nginx_status 显示:

Active connections: 2
server accepts handled requests
 12345 12345 123456
Reading: 0 Writing: 1 Waiting: 1
  • Active connections:当前活动连接数
  • accepts:已接受的连接数
  • handled:已处理的连接数
  • requests:已处理的请求数
  • Reading:正在读取请求头的连接数
  • Writing:正在响应请求的连接数
  • Waiting:空闲连接数

12. 常用命令

12.1 启动和停止

bash
# 启动 Nginx
sudo systemctl start nginx

# 停止 Nginx
sudo systemctl stop nginx

# 重启 Nginx
sudo systemctl restart nginx

# 重新加载配置
sudo systemctl reload nginx

# 查看状态
sudo systemctl status nginx

12.2 配置测试

bash
# 测试配置文件
sudo nginx -t

# 显示配置文件
sudo nginx -T

12.3 查看版本

bash
# 查看 Nginx 版本
nginx -v

# 查看详细版本信息
nginx -V

12.4 查看进程

bash
# 查看 Nginx 进程
ps aux | grep nginx

# 查看 Nginx 端口
netstat -tlnp | grep nginx

13. 常见问题

13.1 502 Bad Gateway

问题:502 Bad Gateway 错误

解决方案

  1. 检查后端服务是否运行
  2. 检查后端服务端口是否正确
  3. 检查防火墙设置
  4. 检查 Nginx 配置

13.2 504 Gateway Timeout

问题:504 Gateway Timeout 错误

解决方案

  1. 增加 proxy_read_timeout
  2. 增加 proxy_connect_timeout
  3. 检查后端服务性能
  4. 优化后端服务代码

13.3 413 Request Entity Too Large

问题:上传文件失败,提示 413 错误

解决方案

nginx
http {
    client_max_body_size 100M;
}

13.4 403 Forbidden

问题:访问被禁止

解决方案

  1. 检查文件权限
  2. 检查 Nginx 用户权限
  3. 检查 IP 白名单
  4. 检查 SELinux 设置

13.5 配置不生效

问题:修改配置后不生效

解决方案

  1. 检查配置文件语法
  2. 重新加载 Nginx 配置
  3. 检查配置文件位置
  4. 检查 include 路径

14. 注意事项

  1. 配置备份:修改配置前先备份
  2. 测试配置:修改后先测试配置
  3. 平滑重启:使用 reload 而不是 restart
  4. 日志监控:定期查看日志文件
  5. 性能监控:监控系统资源使用
  6. 安全更新:及时更新 Nginx 版本
  7. 权限管理:合理配置文件权限
  8. 防火墙:配置防火墙规则

15. 相关文档