Nginx

概述

Nginx 是一款高性能的 HTTP 服务器和反向代理服务器,以高并发、低资源消耗和丰富的功能模块著称,广泛应用于 Web 服务部署、负载均衡和反向代理场景。

核心功能

  • 静态资源服务:高效托管 HTML、CSS、JavaScript、图片等静态文件
  • 反向代理:将请求转发至后端应用服务器(如 Tomcat、Node.js、Gunicorn)
  • 负载均衡:支持轮询、加权轮询、IP Hash 等多种策略
  • SSL/TLS 终止:支持 HTTPS 配置和证书管理
  • 缓存加速:支持静态内容缓存和代理缓存
  • 限流与安全:支持访问限制、IP 黑名单、DDoS 防护

Docker 部署

1. 初始化目录和配置文件

# 创建目录
mkdir -p ./nginx/html ./nginx/conf.d

# 拷贝 nginx 默认配置文件
docker run --rm -it nginx:latest cat /etc/nginx/conf.d/default.conf > ./nginx/conf.d/default.conf
docker run --rm -it nginx:latest cat /etc/nginx/nginx.conf > ./nginx/nginx.conf
docker run --rm -it nginx:latest cat /usr/share/nginx/html/index.html > ./nginx/html/index.html

2. 创建 Docker Compose 编排文件

docker-compose.yaml

version: '3.8'
services:
  nginx:
    image: nginx:latest
    container_name: nginx
    restart: always
    environment:
      - TZ=Asia/Shanghai
    ports:
      - "80:80"
    deploy:
      resources:
        limits:
          cpus: "0.5"
          memory: "512M"
    volumes:
      - ./nginx/html:/usr/share/nginx/html
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf

3. 启动服务

docker compose up -d

查看日志:

docker logs nginx -f --tail=50

YUM 部署

1. 安装 Nginx

yum install -y nginx nginx-all-modules

2. 修改文件打开数限制

编辑 /usr/lib/systemd/system/nginx.service,添加:

LimitNOFILE=65000

3. 启动并设置开机自启

systemctl daemon-reload
systemctl start nginx
systemctl enable nginx
systemctl status nginx

常用管理命令

操作 Docker 命令 YUM 命令
启动 docker compose up -d systemctl start nginx
停止 docker compose stop systemctl stop nginx
重启 docker compose restart systemctl restart nginx
查看状态 docker compose ps systemctl status nginx
查看日志 docker logs nginx -f tail -f /var/log/nginx/access.log
重载配置 docker compose restart systemctl reload nginx

配置示例

80 与 443 同时使用

server {
    listen 80;
    listen 443 ssl;
    server_name test.hxq.cn;

    # 证书配置
    ssl_certificate ssl/test.hxq.cn.crt;
    ssl_certificate_key ssl/test.hxq.cn.key;
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout 10m;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # 压缩配置
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types application/octet-stream application/atom+xml application/geo+json application/javascript application/x-javascript application/json application/ld+json application/manifest+json application/rdf+xml application/rss+xml application/xhtml+xml application/xml font/eot font/otf font/ttf image/svg+xml text/css text/javascript text/plain text/xml;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_pass http://192.168.1.2:8080;
    }
}

80 强制跳转 443

server {
    listen 80;
    server_name test.hxq.cn;
    return 301 https://$host$request_uri;
}

传递真实 IP

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;

指定 Host 转发

# 方案1:传递原始客户端请求的 Host(推荐)
proxy_set_header Host $host;

# 方案2:传递自定义 Host(后端服务指定域名时使用)
# proxy_set_header Host backend.hxq.cn;

支持 URL 下划线

# 开启请求头中的下划线支持(默认 off)
underscores_in_headers on;

跨域配置

add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS,PATCH;
add_header Access-Control-Allow-Headers Origin,Content-Type,Accept,Authorization,X-Real-IP,X-Forwarded-For;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Max-Age 86400;

if ($request_method = OPTIONS) {
    return 204;
}

WebSocket 长连接配置

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

日志格式配置

log_format main '$remote_addr - $remote_user [$time_local] '
                'requesthost:"$http_host"; '
                '"$request" '
                'requesttime:"$request_time"; '
                '$status $body_bytes_sent '
                '"$http_referer" '
                'request_body:"$request_body" '
                'content_type:"$http_content_type" '
                'request_length:"$request_length" '
                'upstream_response_time:"$upstream_response_time" '
                'upstream_addr:"$upstream_addr" '
                '"$http_user_agent" '
                'x_forwarded_for:"$http_x_forwarded_for" '
                'access_control_request_headers:"$http_access_control_request_headers"';

root 与 alias 对比

对比项 root 指令 alias 指令
路径拼接规则 最终路径 = root 路径 + 完整请求 URI 最终路径 = alias 路径 +(请求 URI - location 匹配部分)
生效层级 http、server、location 均可 仅 location 块中有效
目录末尾斜杠 无强制要求 建议添加 /,避免多级路径拼接错误
适用场景 匹配整个网站根目录、常规静态文件目录 匹配局部路径、需要替换 URI 前缀的场景

示例说明

# root:请求 /images/logo.png → /var/www/html/images/logo.png
location /images/ {
    root /var/www/html;
}

# alias:请求 /images/logo.png → /var/www/static/logo.png
location /images/ {
    alias /var/www/static/;
}

proxy_pass 斜杠说明

配置 请求 URI 转发 URI
proxy_pass http://backend(不加 / /api/user /api/user
proxy_pass http://backend/(加 / /api/user /user

规则总结

  • 末尾不加 /:保留完整请求 URI
  • 末尾 /:剔除 location 匹配的前缀部分

常见问题

Q:Nginx 启动失败,提示端口被占用?

# 查看端口占用
netstat -tlnp | grep -E '80|443'

# 修改 Nginx 监听端口
server {
    listen 8080;  # 改为其他端口
}

Q:配置修改后不生效?

检查配置语法:

nginx -t

如语法正确,执行重载:

systemctl reload nginx
# 或
docker compose restart nginx

Q:反向代理出现 502 Bad Gateway?

  1. 确认后端服务是否正常运行:
curl http://192.168.1.2:8080
  1. 检查 proxy_pass 地址是否正确
  2. 检查防火墙是否放行后端端口

Q:上传文件大小受限?

在 Nginx 配置中添加:

http {
    client_max_body_size 100M;
}

Q:如何限制访问 IP?

location /admin/ {
    allow 192.168.1.0/24;
    deny all;
}

参考链接