Nginx 基础到进阶 MDX 示例

2025年6月18日

Nginx 是一款高性能的 Web 服务器和反向代理服务器,广泛应用于网站架构中。本文将通过 MDX 形式,系统介绍 Nginx 的常用配置与进阶用法。

Nginx 简介

Nginx(engine x)是一款开源、高性能的 HTTP 和反向代理服务器,也可作为 IMAP/POP3/SMTP 代理服务器。

安装 Nginx

macOS

brew install nginx

Ubuntu/Debian

sudo apt update
sudo apt install nginx

启动与管理

# 启动 Nginx
sudo nginx
# 检查配置文件语法
sudo nginx -t
# 重新加载配置
sudo nginx -s reload
# 停止 Nginx
sudo nginx -s stop

基本配置结构

Nginx 配置文件通常位于 /etc/nginx/nginx.conf,结构如下:

user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

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

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
}

静态资源服务

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

反向代理

Nginx 可作为反向代理,将请求转发到后端服务。

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

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

负载均衡

http {
    upstream backend {
        server 127.0.0.1:3001;
        server 127.0.0.1:3002;
    }
    server {
        listen 80;
        location / {
            proxy_pass http://backend;
        }
    }
}

HTTPS 配置

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate /etc/nginx/ssl/example.crt;
    ssl_certificate_key /etc/nginx/ssl/example.key;

    location / {
        root /var/www/html;
        index index.html;
    }
}

常用优化

Gzip 压缩

gzip on;
gzip_types text/plain application/javascript text/css application/xml;

缓存静态资源

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    access_log off;
}

进阶用法

URL 重写

location /old-path/ {
    rewrite ^/old-path/(.*)$ /new-path/$1 permanent;
}

限流配置

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    server {
        location /api/ {
            limit_req zone=one burst=5;
        }
    }
}

基本认证

location /admin/ {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

常用命令

以下是 Nginx 常用命令,便于日常管理和排查:

# 查看 Nginx 版本
nginx -v
# 查看 Nginx 编译参数
nginx -V
# 查看 Nginx 配置文件路径
nginx -t
# 以非守护进程方式启动(前台运行,调试用)
sudo nginx -g 'daemon off;'
# 列出所有 Nginx 进程
ps aux | grep nginx
# 平滑重启 Nginx
sudo nginx -s reload
# 停止 Nginx(快速关闭)
sudo nginx -s stop
# 优雅关闭 Nginx(处理完当前请求后关闭)
sudo nginx -s quit
# 重新打开日志文件(如 logrotate 后)
sudo nginx -s reopen
# 查看监听端口
sudo netstat -tulnp | grep nginx
# 查看 Nginx 配置语法是否正确
sudo nginx -t

常见问题排查

  • 查看 Nginx 日志:/var/log/nginx/error.log
  • 检查端口占用:sudo lsof -i:80
  • 配置变更后需 reload

参考资料

Az_Goody