欢迎光临
我们一直在努力

Nginx 使用指南

Nginx 使用指南

Nginx(发音 “engine-x”)是一个高性能的 HTTP 和反向代理服务器,以其高并发、低内存消耗和稳定性著称。它最初为解决 C10K 问题而设计,采用事件驱动的异步架构,能够处理大量并发连接。Nginx 主要用作 Web 服务器、反向代理、负载均衡器和 HTTP 缓存。


一、安装与基本管理

1.1 在 Ubuntu/Debian 上安装

sudo apt update
sudo apt install nginx

1.2 在 CentOS/RHEL 上安装

sudo yum install epel-release
sudo yum install nginx
# 较新版本使用 dnf
sudo dnf install nginx

1.3 在 macOS 上安装(使用 Homebrew)

brew install nginx

1.4 在 Windows 上安装

  • 访问 nginx.org,下载 Stable version 稳定版 Windows 压缩包
  • 将压缩包解压到不含中文或空格的目录,如 D:\\nginx
  • 双击 nginx.exe 运行,通过任务管理器确认 nginx.exe 进程存在即表示启动成功
  • 1.5 服务管理命令(systemd)

    # 启动 Nginx
    sudo systemctl start nginx

    # 停止 Nginx
    sudo systemctl stop nginx

    # 重启 Nginx
    sudo systemctl restart nginx

    # 重新加载配置(不中断服务,推荐)
    sudo systemctl reload nginx

    # 查看运行状态
    sudo systemctl status nginx

    # 设置开机自启
    sudo systemctl enable nginx


    二、核心概念

    2.1 配置文件结构

    Nginx 的主配置文件通常位于:

    • Linux: /etc/nginx/nginx.conf
    • macOS: /usr/local/etc/nginx/nginx.conf
    • Windows: {解压目录}/conf/nginx.conf

    典型的目录结构(Debian/Ubuntu 风格):

    /etc/nginx/
    ├── nginx.conf # 主配置文件
    ├── conf.d/ # 额外配置文件目录
    ├── sites-available/ # 可用站点配置文件
    └── sites-enabled/ # 已启用站点配置文件(软链接)

    2.2 基本配置示例

    # 全局设置(main 上下文)
    user nginx;
    worker_processes auto;
    error_log /var/log/nginx/error.log;
    pid /run/nginx.pid;

    # 事件模块配置
    events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
    }

    # HTTP 模块配置(核心部分)
    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;

    # 模块化配置引入
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    # 虚拟主机配置(server 块)
    server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.html index.htm;

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

    2.3 核心上下文

    上下文说明
    main 全局配置,如 worker 进程数、用户、错误日志等
    events 事件驱动相关配置,如连接数、I/O 模型等
    http HTTP 协议相关配置,包含所有 Web 服务指令
    server 虚拟主机配置,定义域名、端口和网站根目录
    location URL 路由规则,匹配特定路径并配置相应处理方式
    upstream 后端服务器组定义,用于负载均衡

    2.4 配置加载顺序

  • Nginx 加载主配置文件 nginx.conf
  • 处理 http 块中的 include 指令,按文件名顺序加载
  • 加载 conf.d/*.conf 和 sites-enabled/* 中的所有配置
  • 如果同一指令在多个文件中出现,以最后加载的为准
  • server 块按 listen 端口和 server_name 优先级匹配请求

  • 三、Web 服务器基础配置

    3.1 最简单的静态网站

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

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

    3.2 处理不同文件类型

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

    # 默认首页
    index index.html index.php;

    # 处理 PHP 请求(通过 FastCGI 转发)
    location ~ \\.php$ {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # 图片缓存设置
    location ~* \\.(jpg|jpeg|png|gif|ico|svg)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    }

    # CSS/JS 缓存
    location ~* \\.(css|js)$ {
    expires 7d;
    add_header Cache-Control "public, immutable";
    }
    }

    3.3 重写规则

    server {
    listen 80;
    server_name example.com;

    # 强制 HTTPS 重定向
    return 301 https://$server_name$request_uri;
    }

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

    # URL 重写(永久重定向)
    rewrite ^/old-page$ /new-page permanent;

    # 条件重写(仅对特定 User-Agent)
    if ($http_user_agent ~* "bot|crawler|spider") {
    rewrite ^ /bot-handler last;
    }

    # 路径重写(隐藏真实路径)
    location /api/ {
    rewrite ^/api/(.*)$ /api/v2/$1 break;
    proxy_pass http://backend_server;
    }
    }


    四、反向代理配置

    4.1 基本反向代理

    反向代理是 Nginx 最常见的用途,它将客户端请求转发给后端服务器,然后将响应返回给客户端。这种方式可以隐藏后端服务器的真实 IP 和端口,同时实现负载均衡和请求缓冲。

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

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

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

    4.2 代理 WebSocket

    WebSocket 协议与普通 HTTP 不同,需要额外配置以支持持久连接。Nginx 1.3.13 以上版本对 WebSocket 有原生支持:

    location /ws/ {
    proxy_pass http://127.0.0.1:3001;
    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_connect_timeout 3600s;
    proxy_send_timeout 3600s;
    proxy_read_timeout 3600s;
    }

    4.3 代理多个后端(负载均衡)

    upstream backend_servers {
    # 负载均衡算法(默认轮询)
    server 127.0.0.1:3000 weight=3; # 权重 3
    server 127.0.0.1:3001 weight=1;
    server 127.0.0.1:3002 backup; # 备用服务器

    # 启用健康检查
    keepalive 32;
    }

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

    location / {
    proxy_pass http://backend_servers;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    }
    }

    4.4 负载均衡算法

    算法配置指令说明
    轮询 默认 按顺序轮流分配
    权重轮询 weight=n 按权重比例分配
    最少连接 least_conn; 分配给活跃连接数最少的服务器
    IP 哈希 ip_hash; 根据客户端 IP 哈希分配,保证同一 IP 固定到同一台服务器
    随机 random; 随机选择,可配合 two 指令优化

    upstream example {
    # 使用 IP 哈希(适合会话保持场景)
    ip_hash;
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    }

    upstream example2 {
    # 最少连接 + 权重
    least_conn;
    server 127.0.0.1:3000 weight=2;
    server 127.0.0.1:3001 weight=1;
    }

    4.5 服务器健康检查

    upstream backend {
    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3001 max_fails=2 fail_timeout=20s;
    server 127.0.0.1:3002 down; # 标记为下线
    }

    # 主动健康检查(需要 nginx-plus 或第三方模块)
    location /health {
    proxy_pass http://backend;
    health_check interval=5s fails=3 passes=2 uri=/health;
    }


    五、HTTPS 与 SSL/TLS 配置

    5.1 生成 SSL 证书(自签名)

    # 生成私钥
    openssl genrsa -out server.key 2048

    # 生成证书签名请求
    openssl req -new -key server.key -out server.csr

    # 生成自签名证书(有效期 365 天)
    openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

    5.2 基本 HTTPS 配置

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

    # SSL 证书配置
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

    # SSL 协议和安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;

    # HSTS(强制 HTTPS)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    root /var/www/example;
    }

    5.3 HTTP 自动跳转 HTTPS

    server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
    }

    # 或使用更复杂的写法
    server {
    listen 80;
    server_name example.com;
    # 对所有请求返回 301 永久重定向
    rewrite ^(.*)$ https://$host$1 permanent;
    }

    5.4 完整的安全配置

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

    # SSL 证书
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # 强制使用 TLS 1.2+
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

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

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

    root /var/www/example;
    }


    六、性能优化

    6.1 worker 进程配置

    # 自动匹配 CPU 核心数
    worker_processes auto;

    # 每个 worker 的连接数(根据系统资源调整)
    events {
    worker_connections 10240;
    use epoll;
    multi_accept on;
    }

    6.2 静态文件缓存

    location ~* \\.(jpg|jpeg|png|gif|ico|css|js)$ {
    root /var/www/example;
    expires 30d;
    add_header Cache-Control "public, immutable";
    # 启用 gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/javascript;
    # 打开文件缓存
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
    }

    6.3 Gzip 压缩

    http {
    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/atom+xml
    image/svg+xml;
    gzip_disable "msie6";
    gzip_min_length 1024; # 小于 1KB 的文件不压缩
    gzip_buffers 16 8k;
    }

    6.4 缓冲区调优

    http {
    # 客户端请求缓冲区
    client_body_buffer_size 128k;
    client_max_body_size 10M;

    # 代理缓冲区
    proxy_buffer_size 4k;
    proxy_buffers 32 4k;
    proxy_busy_buffers_size 64k;

    # FastCGI 缓冲区
    fastcgi_buffer_size 4k;
    fastcgi_buffers 32 4k;
    fastcgi_busy_buffers_size 64k;
    }

    6.5 连接超时优化

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

    # 客户端超时
    client_header_timeout 10;
    client_body_timeout 10;

    # 代理超时
    proxy_connect_timeout 60;
    proxy_send_timeout 60;
    proxy_read_timeout 60;

    # 发送超时
    send_timeout 60;
    }

    6.6 限流配置

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

    server {
    location /api/ {
    # 每个 IP 每秒最多 10 个请求
    limit_req zone=perip burst=20 nodelay;
    # 每个 IP 最多 10 个并发连接
    limit_conn addr 10;

    proxy_pass http://backend;
    }
    }
    }


    七、日志管理

    7.1 日志格式定义

    http {
    # 标准日志格式
    log_format main '$remote_addr – $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    # JSON 格式日志(便于 ELK 等日志系统分析)
    log_format json escape=json '{'
    '"time_local":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"request":"$request",'
    '"status":$status,'
    '"body_bytes_sent":$body_bytes_sent,'
    '"http_referer":"$http_referer",'
    '"http_user_agent":"$http_user_agent"'
    '}';

    access_log /var/log/nginx/access.log main;
    access_log /var/log/nginx/access.json.log json;
    error_log /var/log/nginx/error.log warn;
    }

    7.2 按站点分离日志

    server {
    server_name example.com;
    access_log /var/log/nginx/example.com.access.log main;
    error_log /var/log/nginx/example.com.error.log;

    # 特定路径不记录日志
    location /health {
    access_log off;
    return 200 "OK";
    }
    }

    7.3 日志轮转(logrotate)

    创建 /etc/logrotate.d/nginx 配置文件:

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

    手动执行轮转:

    sudo logrotate -vf /etc/logrotate.d/nginx


    八、安全配置

    8.1 隐藏 Nginx 版本

    http {
    # 隐藏版本号,防止信息泄露
    server_tokens off;
    }

    # 或仅对特定 server 隐藏
    server {
    server_tokens off;
    }

    8.2 限制访问

    server {
    # 限制 IP 访问
    location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
    proxy_pass http://backend;
    }

    # 密码保护
    location /private/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    # 创建密码文件:htpasswd -c /etc/nginx/.htpasswd username
    }
    }

    8.3 防止常见攻击

    server {
    # 防止目录遍历
    location ~ /\\. {
    deny all;
    }

    # 防止 SQL 注入(通过 User-Agent 过滤)
    if ($http_user_agent ~* (sqlmap|nmap|nikto) ) {
    return 444;
    }

    # 防止跨站脚本
    add_header X-XSS-Protection "1; mode=block";

    # 防止 MIME 类型嗅探
    add_header X-Content-Type-Options "nosniff";
    }

    8.4 限制请求方法

    server {
    # 只允许 GET 和 POST 方法
    if ($request_method !~ ^(GET|POST)$) {
    return 405;
    }

    # 更精确的控制
    location /api/ {
    limit_except GET {
    allow 192.168.1.0/24;
    deny all;
    }
    proxy_pass http://backend;
    }
    }


    九、常见场景配置

    9.1 前后端分离(SPA)

    server {
    listen 80;
    server_name app.example.com;
    root /var/www/spa/dist;

    # SPA 路由处理(所有请求返回 index.html)
    location / {
    try_files $uri $uri/ /index.html;
    }

    # API 代理
    location /api/ {
    proxy_pass http://backend_server:8080/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    }
    }

    9.2 同一端口配置多个站点(基于域名)

    server {
    listen 80;
    server_name site1.com www.site1.com;
    root /var/www/site1;
    }

    server {
    listen 80;
    server_name site2.com www.site2.com;
    root /var/www/site2;
    }

    9.3 同一域名配置多个站点(基于路径)

    server {
    listen 80;
    server_name example.com;

    location /app1/ {
    alias /var/www/app1/;
    index index.html;
    }

    location /app2/ {
    alias /var/www/app2/;
    index index.html;
    }
    }

    9.4 静态资源 CDN 加速

    server {
    listen 80;
    server_name static.example.com;
    root /var/www/static;

    # 设置缓存头
    location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg|webp)$ {
    expires max;
    add_header Cache-Control "public, immutable";
    add_header Access-Control-Allow-Origin "*";
    }
    }

    9.5 代理 PHP-FPM

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

    index index.php;

    location ~ \\.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    # 或使用 TCP:fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    }
    }

    9.6 代理 Node.js 应用

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

    location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;

    # 添加超时配置
    proxy_connect_timeout 120s;
    proxy_send_timeout 120s;
    proxy_read_timeout 120s;
    }
    }

    9.7 代理 Python 应用(Gunicorn/uWSGI)

    # Gunicorn
    location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # uWSGI
    location / {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:3031;
    }


    十、调试与故障排查

    10.1 测试配置文件

    # 测试配置文件语法(在修改配置后使用,推荐)
    sudo nginx -t

    # 显示配置文件路径
    sudo nginx -T

    # 测试后如果显示 "syntax is ok" 和 "test is successful" 表示配置正确

    10.2 查看错误日志

    # 实时查看错误日志
    sudo tail -f /var/log/nginx/error.log

    # 查看最近 100 行错误
    sudo tail -100 /var/log/nginx/error.log

    # 查找特定错误
    grep "error" /var/log/nginx/error.log

    10.3 调试模式运行

    # 前台运行,输出详细日志
    sudo nginx -g "daemon off; error_log /dev/stderr debug;"

    # 以调试模式运行(需要编译时启用 debug)
    sudo nginx -g "debug_connection 192.168.1.1;"

    10.4 查看访问日志

    # 实时查看访问日志
    sudo tail -f /var/log/nginx/access.log

    # 按 IP 统计访问量
    sudo cat /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr

    # 统计状态码分布
    sudo cat /var/log/nginx/access.log | awk '{print $9}' | sort | uniq -c | sort -nr

    10.5 常用诊断命令

    # 检查 Nginx 是否运行
    ps aux | grep nginx

    # 检查端口是否监听
    sudo netstat -tlnp | grep nginx

    # 查看进程 PID
    cat /run/nginx.pid

    # 平滑重启
    sudo kill -HUP $(cat /run/nginx.pid)

    # 优雅停止
    sudo kill -QUIT $(cat /run/nginx.pid)

    # 强制停止
    sudo kill -TERM $(cat /run/nginx.pid)


    十一、高可用与集群

    11.1 Nginx + Keepalived 高可用

    # 安装 Keepalived
    sudo apt install keepalived

    # 配置 /etc/keepalived/keepalived.conf
    vrrp_script check_nginx {
    script "/etc/keepalived/check_nginx.sh"
    interval 2
    weight 2
    }

    vrrp_instance VI_1 {
    state MASTER # BACKUP 节点为 BACKUP
    interface eth0
    virtual_router_id 51
    priority 100 # BACKUP 节点为 90
    advert_int 1

    authentication {
    auth_type PASS
    auth_pass 1111
    }

    virtual_ipaddress {
    192.168.1.100/24 # 虚拟 IP
    }

    track_script {
    check_nginx
    }
    }

    11.2 健康检查脚本

    #!/bin/bash
    # /etc/keepalived/check_nginx.sh
    if [ -f /var/run/nginx.pid ]; then
    exit 0
    else
    exit 1
    fi

    11.3 多级代理架构

    客户端 → Nginx(负载均衡器)→ Nginx(应用服务器)→ 后端服务

    # 第一层:负载均衡器
    upstream app_servers {
    server 192.168.1.10:80;
    server 192.168.1.11:80;
    server 192.168.1.12:80;
    }

    server {
    listen 80;
    location / {
    proxy_pass http://app_servers;
    }
    }

    # 第二层:应用服务器
    server {
    listen 80;
    location / {
    proxy_pass http://127.0.0.1:3000;
    }
    }


    十二、与 Docker 配合使用

    12.1 使用官方镜像

    # 拉取官方镜像
    docker pull nginx:alpine

    # 运行容器
    docker run –name my-nginx -p 80:80 -d nginx

    12.2 自定义配置

    # 使用自定义配置
    docker run –name my-nginx \\
    -v /path/to/nginx.conf:/etc/nginx/nginx.conf:ro \\
    -v /path/to/html:/usr/share/nginx/html:ro \\
    -p 80:80 -d nginx

    12.3 Docker Compose 示例

    version: '3.8'

    services:
    nginx:
    image: nginx:alpine
    container_name: nginxproxy
    ports:
    "80:80"
    "443:443"
    volumes:
    ./nginx.conf:/etc/nginx/nginx.conf:ro
    ./conf.d:/etc/nginx/conf.d:ro
    ./ssl:/etc/nginx/ssl:ro
    ./html:/usr/share/nginx/html:ro
    ./logs:/var/log/nginx
    depends_on:
    app

    app:
    build: .
    container_name: appserver
    expose:
    "3000"


    十三、常用变量速查

    变量说明
    $remote_addr 客户端 IP 地址
    $remote_user 客户端认证用户名
    $time_local 本地时间
    $request 完整请求行(方法 + URI + 协议)
    $request_uri 完整请求 URI(含参数)
    $uri 当前请求 URI(不含参数)
    $args 请求参数
    $status 响应状态码
    $body_bytes_sent 响应体字节数
    $http_referer Referer 头
    $http_user_agent User-Agent 头
    $http_x_forwarded_for X-Forwarded-For 头
    $host 请求的域名
    $server_name 服务器名称
    $server_port 服务器端口
    $scheme 请求协议(http/https)
    $request_method 请求方法(GET/POST 等)
    $content_type Content-Type 头
    $content_length Content-Length 头
    $document_root 网站的根目录路径
    $document_uri 同 $uri
    $query_string 同 $args
    $cookie_name 指定名称的 Cookie 值

    十四、常见问题与解决

    问题解决方法
    502 Bad Gateway 检查后端服务是否运行;检查防火墙是否允许端口
    504 Gateway Timeout 增加 proxy_read_timeout;检查后端响应速度
    413 Request Entity Too Large 增加 client_max_body_size
    403 Forbidden 检查目录权限;检查 index 指令是否正确
    404 Not Found 检查 root 路径是否正确;检查文件是否存在
    无法加载静态资源 检查 location 规则是否正确;检查文件路径权限
    端口被占用 使用 sudo netstat -tlnp 查看占用;更换端口
    HTTPS 证书错误 检查证书路径和有效期;使用 Let’s Encrypt 更新
    日志文件过大 配置 logrotate;设置日志切割策略
    Nginx 无法启动 使用 nginx -t 测试配置;检查错误日志
    内存占用过高 减少 worker_connections;调整缓冲区大小
    缓存不生效 检查 Cache-Control 头设置;检查文件修改时间

    十五、快速参考

    常用命令速查

    # 启动
    sudo systemctl start nginx

    # 停止
    sudo systemctl stop nginx

    # 重启
    sudo systemctl restart nginx

    # 重载配置(平滑)
    sudo systemctl reload nginx

    # 测试配置
    sudo nginx -t

    # 查看状态
    sudo systemctl status nginx

    # 启用开机自启
    sudo systemctl enable nginx

    # 查看版本
    nginx -v
    nginx -V # 显示编译参数

    常用配置文件目录

    系统主配置文件站点配置
    Debian/Ubuntu /etc/nginx/nginx.conf /etc/nginx/sites-enabled/
    CentOS/RHEL /etc/nginx/nginx.conf /etc/nginx/conf.d/
    macOS (Homebrew) /usr/local/etc/nginx/nginx.conf /usr/local/etc/nginx/servers/
    Windows {解压目录}/conf/nginx.conf {解压目录}/conf/conf.d/

    端口说明

    端口用途
    80 HTTP(默认)
    443 HTTPS(SSL/TLS)
    8080 备用 HTTP
    8443 备用 HTTPS

    十六、资源与参考

    • 官方文档: https://nginx.org/en/docs/
    • 中文文档: https://nginx.org/zh/
    • 配置示例: https://github.com/nginx/nginx/tree/master/conf
    • Nginx 可视化配置生成器: https://nginxconfig.io/
    • Let’s Encrypt 免费 SSL: https://letsencrypt.org/zh-cn/
    • Nginx 性能调优指南: https://www.nginx.com/blog/tuning-nginx/

    十七、配置模板

    基础静态站点模板

    server {
    listen 80;
    server_name example.com;

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

    # Gzip 压缩
    gzip on;
    gzip_types text/plain text/css text/xml text/javascript application/javascript;

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

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

    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root /usr/share/nginx/html;
    }
    }

    反向代理模板

    upstream backend {
    server 127.0.0.1:3000 weight=2;
    server 127.0.0.1:3001 weight=1;
    keepalive 32;
    }

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

    access_log /var/log/nginx/api.access.log main;
    error_log /var/log/nginx/api.error.log;

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

    proxy_http_version 1.1;
    proxy_set_header Connection "";

    # 超时设置
    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;
    }

    # 健康检查端点
    location /health {
    access_log off;
    return 200 "OK";
    }
    }


    结语

    Nginx 是一个功能强大且灵活的服务器软件,掌握其核心配置可以应对绝大多数 Web 服务场景。建议从基础配置开始,逐步深入反向代理、负载均衡和性能优化。在生产环境中,务必使用 nginx -t 测试配置,并优先使用 reload 而非 restart 来更新配置。

    更多高级功能(如 Lua 脚本扩展、流媒体代理、动态模块加载等)可以参考官方文档进一步学习。

    祝使用愉快!🚀

    赞(0)
    未经允许不得转载:171主机测评 » Nginx 使用指南
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址