Nginx 安装配置

在 Ubuntu/CentOS 上装 Nginx、配虚拟主机与反向代理、上 HTTPS。

Intermediate
Key Points配置分三层:main、events、http;站点放 conf.d 或 sites-enabled,改完先 nginx -t 再 reload。

安装

Bash
# Ubuntu / Debian
sudo apt update && sudo apt install -y nginx
sudo systemctl enable --now nginx

# RHEL / Rocky
sudo dnf install -y nginx
sudo systemctl enable --now nginx
Bash
nginx -v
systemctl status nginx --no-pager
ss -lntp | grep nginx

目录结构

PathContent
/etc/nginx/nginx.confmain / events / http blocks
/etc/nginx/conf.d/*.confSite configs (RHEL style)
/etc/nginx/sites-enabled/Site configs (Debian style)
/var/log/nginx/access.log, error.log
/usr/share/nginx/htmlDefault static root

一个站点

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

    root /var/www/app;
    index index.html;

    access_log /var/log/nginx/app.access.log;
    error_log  /var/log/nginx/app.error.log warn;

    location /static/ {
        expires 30d;
        add_header Cache-Control "public";
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8080/;
        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_read_timeout 60s;
    }
}
Bash
sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/app
sudo nginx -t
sudo systemctl reload nginx

HTTPS

Bash
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d app.example.com
sudo systemctl status certbot.timer     # 自动续期
NGINX
server {
    listen 443 ssl http2;
    server_name app.example.com;

    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_session_cache   shared:SSL:10m;

    location / { proxy_pass http://127.0.0.1:8080; }
}
server {
    listen 80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

常用排查

SymptomCheck
502 Bad Gatewayerror.log + upstream alive?
504 Gateway Timeoutproxy_read_timeout, slow upstream
413 Request Entity Too Largeclient_max_body_size
Config not appliednginx -t then reload
restart drops every connection; reload is graceful. Always nginx -t first — on a syntax error the reload fails while the old worker keeps serving, which looks like success.

Friends & Partners