[Nginx] Nginx学习手册

Grok生成(2025年10月24日00:06:27)

Nginx 学习手册


目录

  1. Nginx 是什么?
  2. 安装与启动
  3. 配置文件详解
  4. 核心功能实战
  5. 常用配置案例
  6. 故障排查
  7. 性能优化
  8. 快速参考

1. Nginx 是什么?

1.1 简单理解

Nginx 是一个高性能的 Web 服务器反向代理服务器,主要用于:

  • 静态文件服务:快速提供 HTML、图片、CSS、JS 文件
  • 反向代理:将请求转发到后端应用服务器(如 Node.js、PHP、Python)
  • 负载均衡:多个后端服务器间分发流量

1.2 与 Apache 的对比

特性 Nginx Apache
性能 极高(10万+并发) 中等
内存占用 极低(2MB)
静态文件 优秀 一般
动态内容 通过代理 内置支持
配置复杂度 中等 简单

1.3 典型架构

浏览器 → Nginx → 静态文件 | 反向代理 → 后端应用(Node.js/PHP/Tomcat)

2. 安装与启动

2.1 Ubuntu/Debian 安装

# 更新包列表
sudo apt update

# 安装 Nginx
sudo apt install nginx

# 启动服务
sudo systemctl start nginx

# 开机自启
sudo systemctl enable nginx

# 检查状态
sudo systemctl status nginx

2.2 验证安装

# 检查版本
nginx -v

# 测试配置文件
sudo nginx -t

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

2.3 访问测试

浏览器访问http://服务器IP
预期结果:显示 "Welcome to nginx!" 欢迎页面


3. 配置文件详解

3.1 文件位置

/etc/nginx/nginx.conf          # 主配置文件
/etc/nginx/sites-available/    # 站点配置目录
/etc/nginx/sites-enabled/      # 启用站点链接
/var/www/html/                 # 默认网站根目录

3.2 核心结构

# 全局配置
worker_processes 1;           # 工作进程数

# 事件配置
events {
    worker_connections 1024;  # 每个进程最大连接数
}

# HTTP 服务配置
http {
    # MIME 类型
    include       /etc/nginx/mime.types;
    
    # 服务器块(虚拟主机)
    server {
        listen       80;      # 监听端口
        server_name  example.com;  # 域名
        
        location / {          # 路径匹配
            root   /var/www/html;
            index  index.html;
        }
    }
}

3.3 关键概念解释

  • server 块:一个网站配置
  • location 块:URL 路径匹配规则
  • listen:监听端口(80=HTTP,443=HTTPS)
  • root:网站文件目录
  • index:默认首页文件

4. 核心功能实战

4.1 静态网站部署

目标:部署一个简单的 HTML 网站

步骤

  1. 创建网站文件

    sudo mkdir -p /var/www/mysite
    cat > /var/www/mysite/index.html << EOF
    <!DOCTYPE html>
    <html>
    <head><title>My Site</title></head>
    <body><h1>Hello Nginx!</h1></body>
    </html>
    EOF
    
  2. 配置虚拟主机

    sudo nano /etc/nginx/sites-available/mysite
    

    配置文件内容

    server {
        listen 80;
        server_name mysite.local;
        
        root /var/www/mysite;
        index index.html;
        
        location / {
            try_files $uri $uri/ =404;
        }
    }
    
  3. 启用站点

    sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
    
  4. 本地测试

    # 编辑 hosts 文件
    echo "127.0.0.1 mysite.local" | sudo tee -a /etc/hosts
    
    # 浏览器访问
    curl http://mysite.local
    

4.2 反向代理实战

目标:Nginx 代理到 Node.js 应用

前提:安装 Node.js 并运行应用

# 创建简单 Node.js 应用
mkdir ~/nodeapp && cd ~/nodeapp
cat > app.js << EOF
const http = require('http');
http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello from Node.js!');
}).listen(3000);
EOF

# 后台运行
node app.js &

Nginx 配置

server {
    listen 80;
    server_name api.local;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

测试

echo "127.0.0.1 api.local" | sudo tee -a /etc/hosts
curl http://api.local
# 输出:Hello from Node.js!

5. 常用配置案例

5.1 HTTPS 配置(Let's Encrypt)

# 安装 certbot
sudo apt install certbot python3-certbot-nginx

# 获取证书
sudo certbot --nginx -d example.com

# 自动续期
sudo crontab -e
# 添加:0 12 * * * /usr/bin/certbot renew --quiet

Nginx 配置

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

server {
    listen 443 ssl;
    server_name example.com;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    root /var/www/html;
    index index.html;
}

5.2 负载均衡

场景:2个后端服务器(192.168.1.10:3000, 192.168.1.11:3000)

upstream backend {
    server 192.168.1.10:3000 weight=1;
    server 192.168.1.11:3000 weight=1;
}

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

5.3 PHP 支持

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

5.4 静态文件缓存

location ~* \.(jpg|jpeg|png|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

6. 故障排查

6.1 常见错误

错误信息 原因 解决方法
502 Bad Gateway 后端服务未启动 检查后端服务状态
403 Forbidden 权限问题 chmod -R 755 /var/www/
404 Not Found 文件路径错误 检查 root 配置
413 Request Entity Too Large 文件上传限制 client_max_body_size 10M;

6.2 诊断命令

# 检查配置
sudo nginx -t

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

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

# 重启服务
sudo systemctl restart nginx

7. 性能优化

7.1 基础优化配置

worker_processes auto;                    # 自动检测CPU核心数
worker_connections 2048;                  # 增加连接数

# 压缩
gzip on;
gzip_types text/plain application/json;

# 隐藏版本信息
server_tokens off;

7.2 连接超时

keepalive_timeout 65;
client_header_timeout 10s;
client_body_timeout 10s;

8. 快速参考

# ========== 安装启动 ==========
sudo apt install nginx
sudo systemctl start nginx

# ========== 配置测试 ==========
sudo nginx -t
sudo nginx -s reload

# ========== 静态网站 ==========
server {
    listen 80;
    root /var/www/html;
    index index.html;
}

# ========== 反向代理 ==========
location / {
    proxy_pass http://127.0.0.1:3000;
}

# ========== HTTPS ==========
sudo certbot --nginx

# ========== 日志查看 ==========
tail -f /var/log/nginx/error.log
posted on 2025-10-24 00:06  风惊庭前叶  阅读(4)  评论(0)    收藏  举报