Refinex DevHubRefinex DevHub
DocsBlogProjectsSitesChangelogAbout
Assistant
你好,我可以基于当前页面内容回答问题、提炼重点,或者告诉你下一步应该继续读什么。
  1. Docs›
  2. Nginx 安装指南
Overview
Nginx 安装指南
Docker 安装指南
Python 安装指南
Nacos 安装指南
Redis 安装指南
MySQL 安装指南
Maven 安装指南
RocketMQ 安装指南
Homebrew 安装指南
PostgreSQL 安装指南
  1. Docs›
  2. Nginx 安装指南

Nginx 安装指南

Note

版本: Nginx 1.28.x(Stable 稳定版)/ 1.29.x(Mainline 主线版) | 平台: Linux(CentOS Stream 9)/ Docker

默认端口: 80(HTTP)/ 443(HTTPS)

推荐安装方式: ⭐ Nginx 官方仓库 RPM 安装(生产首选)

一、概述

Nginx(engine x)是全球最流行的高性能 HTTP 服务器、反向代理、负载均衡器和内容缓存。由 Igor Sysoev 创建,采用事件驱动、异步非阻塞架构,单机可轻松处理数万并发连接。

1.1 版本选择

分支当前版本更新频率特点适用场景
Stable(稳定版)1.28.3数月一次仅含关键修复,接口稳定生产环境首选
Mainline(主线版)1.29.71-2 月一次含最新功能、修复和安全补丁开发/测试、追求新功能
推荐

生产环境使用 Stable 稳定版。Nginx 官方建议:如果对稳定性没有严格要求,也可直接使用 Mainline(官方在 Mainline 上做的测试更多)。

1.2 安装方式对比

方式版本难度优势适用场景
⭐ Nginx 官方仓库1.28.x(最新稳定)简单版本新、官方维护、一键升级生产首选
CentOS AppStream1.20.x(老旧)最简单系统自带、无需添加源不推荐(版本过旧)
源码编译任意版本复杂完全自定义模块需定制第三方模块
Docker任意版本简单环境隔离、部署一致容器化架构、CI/CD

二、环境准备(CentOS Stream 9)

2.1 安装前检查与卸载旧版本

重要

安装前检查并卸载已有的 Nginx,避免版本冲突和端口占用。

Bash
# 检查是否已安装 Nginx
nginx -v
systemctl status nginx
rpm -qa | grep nginx
​
# 如已安装旧版,先停止并卸载
sudo systemctl stop nginx
sudo systemctl disable nginx
sudo dnf remove nginx
​
# 清理残留配置(可选,建议先备份)
sudo cp -r /etc/nginx /backup/nginx-old-$(date +%Y%m%d)
sudo rm -rf /etc/nginx
sudo rm -rf /var/log/nginx
sudo rm -rf /var/cache/nginx
​
# 清理可能的旧仓库
sudo rm -f /etc/yum.repos.d/nginx.repo
​
# 验证
which nginx 2>/dev/null && echo '未清理干净!' || echo '已清理干净'
ss -tlnp | grep -E ':80 |:443 '

2.2 防火墙配置

Bash
sudo firewall-cmd --permanent --add-service=http    # 80
sudo firewall-cmd --permanent --add-service=https   # 443
sudo firewall-cmd --reload

2.3 SELinux 配置

Bash
# 查看当前状态
getenforce
​
# 如果是 Enforcing,需允许 Nginx 网络连接(反向代理必需)
sudo setsebool -P httpd_can_network_connect 1
​
# 如果 Nginx 需要访问非标准目录
sudo setsebool -P httpd_read_user_content 1

三、安装方式一:Nginx 官方仓库(⭐ 推荐)

安装路径

二进制 /usr/sbin/nginx,配置 /etc/nginx/nginx.conf

3.1 添加 Nginx 官方仓库

Bash
# 安装依赖
sudo dnf install -y dnf-utils
​
# 创建仓库文件
cat > /etc/yum.repos.d/nginx.repo <<'EOF'
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
​
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF
​
# 默认使用 stable 稳定版
# 如需切换到 mainline 主线版:
# sudo yum-config-manager --enable nginx-mainline

3.2 安装 Nginx

Bash
sudo dnf install -y nginx
​
# 验证版本
nginx -v
# 应显示: nginx version: nginx/1.28.x
Tip

首次安装时会提示导入 GPG Key,验证指纹为 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62,确认后接受即可。

3.3 启动与开机自启

Bash
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx
​
# 验证:浏览器访问 http://<服务器IP> 应看到 Nginx 欢迎页
curl -I http://localhost
# 应返回 HTTP/1.1 200 OK

3.4 关键文件路径

文件/目录说明
/etc/nginx/nginx.conf主配置文件
/etc/nginx/conf.d/虚拟主机配置目录(*.conf 自动加载)
/usr/share/nginx/html/默认静态文件根目录
/var/log/nginx/access.log访问日志
/var/log/nginx/error.log错误日志
/var/cache/nginx/缓存目录
/etc/nginx/mime.typesMIME 类型映射

四、安装方式二:源码编译

适用于需要定制模块(如 ngx_http_geoip2_module、ngx_brotli)的场景。

安装路径

默认 /usr/local/nginx/,可通过 --prefix 自定义。

4.1 安装编译依赖

Bash
sudo dnf install -y gcc make pcre2-devel openssl-devel zlib-devel wget

4.2 下载与编译

Bash
cd /opt
wget https://nginx.org/download/nginx-1.28.3.tar.gz
tar -xzf nginx-1.28.3.tar.gz
cd nginx-1.28.3
​
# 配置(常用选项)
./configure \
  --prefix=/etc/nginx \
  --sbin-path=/usr/sbin/nginx \
  --modules-path=/usr/lib64/nginx/modules \
  --conf-path=/etc/nginx/nginx.conf \
  --error-log-path=/var/log/nginx/error.log \
  --http-log-path=/var/log/nginx/access.log \
  --pid-path=/var/run/nginx.pid \
  --lock-path=/var/run/nginx.lock \
  --with-http_ssl_module \
  --with-http_v2_module \
  --with-http_v3_module \
  --with-http_realip_module \
  --with-http_gzip_static_module \
  --with-http_stub_status_module \
  --with-stream \
  --with-stream_ssl_module
​
make
sudo make install

4.3 配置为系统服务

创建 /etc/systemd/system/nginx.service:

Text
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
Bash
sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx

五、安装方式三:Docker 部署

Docker 镜像

nginx:stable(稳定版)/ nginx:stable-alpine(Alpine 轻量版,仅 ~40MB)

5.1 快速启动

Bash
docker run -d \
  --name nginx \
  -p 80:80 \
  -p 443:443 \
  nginx:stable
​
# 验证
curl -I http://localhost

5.2 Docker Compose(生产推荐)

YAML
# docker-compose-nginx.yml
version: '3.8'
services:
  nginx:
    image: nginx:stable
    container_name: nginx-server
    restart: always
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./conf.d:/etc/nginx/conf.d:ro
      - ./html:/usr/share/nginx/html:ro
      - ./certs:/etc/nginx/certs:ro
      - nginx-logs:/var/log/nginx
      - nginx-cache:/var/cache/nginx
    environment:
      - TZ=Asia/Shanghai
    deploy:
      resources:
        limits:
          memory: 512m
​
volumes:
  nginx-logs:
  nginx-cache:
Bash
# 创建目录结构
mkdir -p conf.d html certs
​
# 启动
docker compose -f docker-compose-nginx.yml up -d
​
# 重载配置(无需重启容器)
docker exec nginx-server nginx -s reload
​
# 查看日志
docker logs -f nginx-server

六、核心配置详解

配置文件位置
  • RPM/官方仓库安装:/etc/nginx/nginx.conf + /etc/nginx/conf.d/*.conf
  • 源码编译安装:/etc/nginx/nginx.conf(由 --conf-path 决定)
  • Docker:挂载自定义配置到容器内 /etc/nginx/nginx.conf

6.1 nginx.conf 生产配置模板

Text
# ==========================================
#  Nginx 生产环境主配置 /etc/nginx/nginx.conf
# ==========================================

user  nginx;
worker_processes  auto;                    # 自动匹配 CPU 核心数
worker_rlimit_nofile 65535;                # 单进程最大文件描述符

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  65535;              # 单进程最大并发连接数
    multi_accept on;                       # 一次接受多个连接
    use epoll;                             # Linux 高性能事件模型
}

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" '
                    '$request_time $upstream_response_time';

    access_log  /var/log/nginx/access.log  main;

    # ---------- 性能优化 ----------
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    keepalive_requests 1000;
    types_hash_max_size 2048;

    # ---------- Gzip 压缩 ----------
    gzip  on;
    gzip_min_length 1k;
    gzip_comp_level 4;
    gzip_vary on;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/javascript
               text/xml application/xml application/xml+rss text/javascript
               image/svg+xml;

    # ---------- 安全头 ----------
    server_tokens off;                     # 隐藏版本号
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    # ---------- 客户端限制 ----------
    client_max_body_size 50m;              # 上传文件大小限制
    client_body_buffer_size 128k;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 16k;

    # ---------- 代理缓冲 ----------
    proxy_buffer_size 128k;
    proxy_buffers 4 256k;
    proxy_busy_buffers_size 256k;
    proxy_temp_file_write_size 256k;

    # ---------- 虚拟主机 ----------
    include /etc/nginx/conf.d/*.conf;
}

6.2 配置验证与重载

Bash
# 验证配置语法(修改后必做!)
sudo nginx -t
# 应输出: syntax is ok / test is successful
​
# 平滑重载(不中断服务)
sudo nginx -s reload
​
# 或通过 systemctl
sudo systemctl reload nginx

七、常用场景配置

7.1 静态网站

创建 /etc/nginx/conf.d/static-site.conf:

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

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

    # 防止访问隐藏文件
    location ~ /\. {
        deny all;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
}

7.2 反向代理(Spring Boot / Node.js 等后端服务)

创建 /etc/nginx/conf.d/api-proxy.conf:

Text
upstream backend_api {
    server 127.0.0.1:8080;
    # 多节点负载均衡
    # server 192.168.1.11:8080;
    # server 192.168.1.12:8080;
    keepalive 32;                          # 长连接池
}

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

    location / {
        proxy_pass http://backend_api;
        proxy_http_version 1.1;
        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 Connection "";

        # 超时设置
        proxy_connect_timeout 10s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

7.3 负载均衡

Text
upstream app_cluster {
    # 默认轮询(Round Robin)
    server 192.168.1.11:8080 weight=3;     # 权重
    server 192.168.1.12:8080 weight=2;
    server 192.168.1.13:8080 backup;       # 备用节点

    # 其他策略:
    # least_conn;                          # 最少连接
    # ip_hash;                             # IP 哈希(会话保持)
    # hash $request_uri consistent;        # 一致性哈希
}
策略指令特点适用场景
轮询(默认)按顺序分配请求无状态服务
加权轮询weight=N按权重比例分配服务器性能不均
最少连接least_conn分配给活跃连接最少的节点请求处理时间不均
IP 哈希ip_hash同 IP 固定到同一后端会话保持

7.4 WebSocket 代理

Text
location /ws/ {
    proxy_pass http://backend_api;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 3600s;              # WebSocket 长连接超时
}

八、HTTPS / SSL 配置

证书文件位置

建议统一存放在 /etc/nginx/certs/ 目录下。Let's Encrypt 证书由 Certbot 自动管理在 /etc/letsencrypt/live/<domain>/。

8.1 Let's Encrypt 免费证书(推荐)

Bash
# 安装 Certbot
sudo dnf install -y certbot python3-certbot-nginx
​
# 自动申请并配置(Nginx 插件会自动修改配置)
sudo certbot --nginx -d example.com -d www.example.com
​
# 验证自动续期
sudo certbot renew --dry-run
​
# 自动续期由 systemd timer 管理
sudo systemctl list-timers | grep certbot

8.2 手动 SSL 配置模板

创建 /etc/nginx/conf.d/ssl-example.conf:

Text
# HTTP -> HTTPS 强制跳转
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

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

    # 证书文件
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;

    # SSL 安全参数
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    # HSTS(严格传输安全,启用后浏览器强制 HTTPS)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 223.5.5.5 valid=300s;

    root /var/www/example.com/html;
    index index.html;
}

九、生产环境优化

配置文件

以下优化项均修改 /etc/nginx/nginx.conf。修改后执行 sudo nginx -t && sudo nginx -s reload。

9.1 系统内核参数优化

Bash
cat >> /etc/sysctl.conf <<'EOF'
# Nginx 优化
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
EOF
sysctl -p

9.2 worker 进程调优

Text
worker_processes auto;              # = CPU 核心数
worker_cpu_affinity auto;           # 自动绑定 CPU
worker_rlimit_nofile 65535;         # 文件描述符限制

events {
    worker_connections 65535;        # 理论最大并发 = workers × connections
    multi_accept on;
    use epoll;
}

9.3 连接复用与超时

Text
keepalive_timeout 65;               # 客户端长连接超时
keepalive_requests 1000;            # 单连接最大请求数
reset_timedout_connection on;       # 释放超时连接资源
send_timeout 10;                    # 响应发送超时

9.4 限流与防护

Text
# 在 http 块中定义
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

# 在 server/location 中使用
location /api/ {
    limit_req zone=api_limit burst=20 nodelay;
    limit_conn conn_limit 50;
    proxy_pass http://backend_api;
}

9.5 日志切割

Bash
# 创建 /etc/logrotate.d/nginx
cat > /etc/logrotate.d/nginx <<'EOF'
/var/log/nginx/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}
EOF

十、监控与健康检查

10.1 启用 stub_status 模块

Text
# /etc/nginx/conf.d/status.conf
server {
    listen 8080;
    server_name localhost;

    location /nginx_status {
        stub_status;
        allow 127.0.0.1;                   # 仅允许本地访问
        deny all;
    }
}
Bash
# 查看状态
curl http://127.0.0.1:8080/nginx_status
# Active connections: 10
# server accepts handled requests
#  1234 1234 5678
# Reading: 0 Writing: 1 Waiting: 9

10.2 Prometheus 监控

使用 nginx-prometheus-exporter:

Bash
./nginx-prometheus-exporter \
  -nginx.scrape-uri=http://127.0.0.1:8080/nginx_status

Grafana Dashboard 推荐:Dashboard ID 12708(NGINX by nginxinc)

十一、常见问题与排查

11.1 配置语法错误

现象: nginx -t 报错

解决: 仔细检查报错行号。常见原因:缺少分号 ;、括号不匹配、upstream 名称拼写错误。

11.2 端口被占用

现象: bind() to 0.0.0.0:80 failed (98: Address already in use)

排查:

Bash
ss -tlnp | grep ':80'
# 找到占用进程后 kill 或修改 Nginx 监听端口

11.3 403 Forbidden

排查步骤:

  1. 检查文件权限:ls -la /var/www/...,确保 nginx 用户可读
  2. 检查 SELinux:ausearch -m avc -ts recent,可能需要 restorecon -Rv /var/www/
  3. 检查 index 指令是否匹配目录中的文件

11.4 502 Bad Gateway

排查步骤:

  1. 后端服务是否在运行:curl http://127.0.0.1:8080/health
  2. proxy_pass 地址是否正确
  3. 检查 SELinux:setsebool -P httpd_can_network_connect 1
  4. 查看错误日志:tail -f /var/log/nginx/error.log

11.5 413 Request Entity Too Large

现象: 上传文件超出限制

解决: 在 http 或 server 块中调大 client_max_body_size 100m;

11.6 upstream timed out

现象: 后端响应超时

解决: 调整超时参数:

Text
proxy_connect_timeout 30s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;

十二、快速参考

常用命令速查

操作命令
启动sudo systemctl start nginx
停止sudo systemctl stop nginx
平滑重载配置sudo nginx -s reload
验证配置语法sudo nginx -t
查看版本nginx -v
查看编译参数nginx -V
查看运行进程ps aux | grep nginx
优雅关闭sudo nginx -s quit
强制停止sudo nginx -s stop
重新打开日志sudo nginx -s reopen
查看错误日志tail -f /var/log/nginx/error.log
查看访问日志tail -f /var/log/nginx/access.log
← 上一篇
下一篇 →
一、概述1.1 版本选择1.2 安装方式对比二、环境准备(CentOS Stream 9)2.1 安装前检查与卸载旧版本2.2 防火墙配置2.3 SELinux 配置三、安装方式一:Nginx 官方仓库(⭐ 推荐)3.1 添加 Nginx 官方仓库3.2 安装 Nginx3.3 启动与开机自启3.4 关键文件路径四、安装方式二:源码编译4.1 安装编译依赖4.2 下载与编译4.3 配置为系统服务五、安装方式三:Docker 部署5.1 快速启动5.2 Docker Compose(生产推荐)六、核心配置详解6.1 nginx.conf 生产配置模板6.2 配置验证与重载七、常用场景配置7.1 静态网站7.2 反向代理(Spring Boot / Node.js 等后端服务)7.3 负载均衡7.4 WebSocket 代理八、HTTPS / SSL 配置8.1 Let's Encrypt 免费证书(推荐)8.2 手动 SSL 配置模板九、生产环境优化9.1 系统内核参数优化9.2 worker 进程调优9.3 连接复用与超时9.4 限流与防护9.5 日志切割十、监控与健康检查10.1 启用 stub_status 模块10.2 Prometheus 监控十一、常见问题与排查11.1 配置语法错误11.2 端口被占用11.3 403 Forbidden11.4 502 Bad Gateway11.5 413 Request Entity Too Large11.6 upstream timed out十二、快速参考常用命令速查