Nginx 配置写多了有些细节总记不住,统一整理在这里。

安装

# Debian/Ubuntu
sudo apt install nginx

# Arch Linux
sudo pacman -S nginx

# 启动
sudo systemctl enable --now nginx

配置文件结构

/etc/nginx/
├── nginx.conf          # 主配置文件
├── conf.d/             # 通常在这里放站点配置
└── sites-enabled/      # 部分发行版用这个目录

nginx.conf 主体结构:

worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    include conf.d/*.conf;
}

静态站点

server {
    listen 80;
    server_name example.com;

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

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

HTTPS 配置

有了证书之后:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;

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

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

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

# HTTP 跳转 HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

反向代理

把请求转发到后端服务:

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

    # SSL 配置省略...

    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;
    }
}

常用 location 匹配

# 精确匹配
location = /favicon.ico { }

# 前缀匹配
location /api/ { }

# 正则匹配(区分大小写)
location ~ \.php$ { }

# 正则匹配(不区分大小写)
location ~* \.(jpg|jpeg|png|gif)$ {
    expires 30d;
}

限速和限流

# 定义限流区域(在 http 块中)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
    }
}

常用命令

# 检查配置语法
nginx -t

# 重新加载配置(不中断服务)
nginx -s reload

# 查看 Nginx 版本和编译参数
nginx -V

修改配置后一定要先 nginx -t 检查语法,没问题再 reload,避免配置写错导致服务挂掉。