Nginx 教程

Nginx (发音为"engine X")是一款高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。由俄罗斯程序员Igor Sysoev开发,首次公开发布于2004年。

Nginx 的主要特点

  1. 高性能:采用事件驱动的异步非阻塞处理方式,能够处理大量并发连接
  2. 低内存消耗:相比其他Web服务器,Nginx在保持高并发的同时内存消耗很低
  3. 高稳定性:即使在高负载情况下也能保持低资源消耗和高性能
  4. 模块化设计:丰富的模块系统,功能可以通过模块扩展
  5. 热部署:支持不停止服务的情况下升级和修改配置

Nginx 常见用途

  • Web服务器
  • 反向代理服务器
  • 负载均衡器
  • HTTP缓存
  • 邮件代理服务器

二、Nginx 安装

Linux 系统安装

Ubuntu/Debian

sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

CentOS/RHEL

sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

Windows 系统安装

  1. 从官网下载Windows版本的Nginx压缩包
  2. 解压到指定目录
  3. 运行nginx.exe

验证安装

在浏览器访问 http://localhost,如果看到Nginx欢迎页面,说明安装成功。

三、Nginx 基本配置

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

  • /etc/nginx/nginx.conf (Linux)
  • conf/nginx.conf (Windows)

配置文件结构

Nginx配置文件由多个块组成,主要包括:

nginx

# 全局块 - 配置影响nginx全局的指令
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# events块 - 配置影响nginx服务器或与用户的网络连接
events {
    worker_connections 1024;
}

# http块 - 可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能
http {
    # server块 - 配置虚拟主机的相关参数
    server {
        # location块 - 配置请求的路由,以及各种页面的处理情况
        location / {
        }
    }
}

常用配置指令

  1. 监听端口

    nginx

    listen 80;
    listen 443 ssl;
    
  2. 服务器名称

    nginx

    server_name example.com www.example.com;
    
  3. 位置块

    nginx

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
    
  4. 错误页面

    nginx

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    

四、Nginx 虚拟主机配置

基于域名的虚拟主机

nginx

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

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

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

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

基于端口的虚拟主机

nginx

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

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

五、Nginx 作为反向代理

反向代理是Nginx最常用的功能之一。

基本反向代理配置

nginx

server {
    listen 80;
    server_name example.com;

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

负载均衡配置

Nginx可以实现简单的负载均衡:

nginx

http {
    upstream myapp {
        server 127.0.0.1:3000 weight=3;
        server 127.0.0.1:3001;
        server 127.0.0.1:3002;
    }

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_pass http://myapp;
        }
    }
}

负载均衡策略:

  • 轮询(默认)
  • 加权轮询(weight)
  • IP哈希(ip_hash)
  • 最少连接(least_conn)

六、Nginx 的 HTTPS 配置

使用 Let's Encrypt 免费证书

  1. 安装certbot工具:
   sudo apt install certbot python3-certbot-nginx
  1. 获取证书:
   sudo certbot --nginx -d example.com -d www.example.com
  1. 自动续期测试:
   sudo certbot renew --dry-run

手动配置HTTPS

nginx

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;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;

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

# HTTP重定向到HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

七、Nginx 性能优化

基础优化配置

nginx

# 工作进程数,通常设置为CPU核心数
worker_processes auto;

# 每个工作进程的最大连接数
events {
    worker_connections 10240;
}

# 启用高效文件传输模式
sendfile on;

# 减少网络数据包数量
tcp_nopush on;

# 保持连接超时时间
keepalive_timeout 65;

# 开启Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

高级优化

  1. 调整缓冲区大小

    nginx

    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 2 1k;
    
  2. 静态文件缓存

    nginx

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 365d;
        add_header Cache-Control "public, no-transform";
    }
    
  3. 启用HTTP/2

    nginx

    listen 443 ssl http2;
    

八、Nginx 日志管理

访问日志配置

nginx

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

错误日志配置

nginx

error_log /var/log/nginx/error.log warn;

日志分割(使用logrotate)

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

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

九、Nginx 常用命令

基本命令

  • 启动Nginx:
  sudo systemctl start nginx
  • 停止Nginx:
  sudo systemctl stop nginx
  • 重启Nginx:
  sudo systemctl restart nginx
  • 重新加载配置(不中断服务):
  sudo systemctl reload nginx
  # 或
  sudo nginx -s reload
  • 检查配置文件语法:
  sudo nginx -t

高级命令

  • 查看Nginx版本:
  nginx -v
  nginx -V  # 显示详细版本和编译参数
  • 平滑升级Nginx:
  kill -USR2 `cat /var/run/nginx.pid`

十、Nginx 常见问题解决

1. 403 Forbidden 错误

可能原因:

  • 文件权限不正确
  • 目录索引文件不存在
  • SELinux限制

解决方案:

sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

2. 502 Bad Gateway 错误

可能原因:

  • 后端服务未运行
  • 代理配置错误

检查后端服务是否正常运行,检查proxy_pass配置。

3. 性能问题

检查:

  • 当前连接数:netstat -anp | grep nginx | wc -l
  • 系统资源:tophtop
  • Nginx状态:配置status模块

十一、Nginx 模块系统

Nginx的功能可以通过模块扩展,常见模块包括:

核心模块

  • ngx_http_core_module - HTTP核心模块
  • ngx_http_access_module - 访问控制模块
  • ngx_http_auth_basic_module - 基本认证模块

第三方模块

  • ngx_http_geoip_module - GeoIP支持
  • ngx_pagespeed - Google PageSpeed模块
  • ngx_cache_purge - 缓存清除模块

动态模块加载示例

nginx

load_module modules/ngx_http_geoip_module.so;

十二、Nginx 与常见应用集成

1. Nginx + PHP-FPM

nginx

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

    index index.php index.html index.htm;

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

2. Nginx + Node.js

nginx

server {
    listen 80;
    server_name example.com;

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

3. Nginx + Python (Django/Flask)

nginx

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /static/ {
        alias /path/to/your/static/files/;
    }
}

十三、Nginx 安全配置

基础安全配置

nginx

# 隐藏Nginx版本号
server_tokens off;

# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";

# 启用XSS保护
add_header X-XSS-Protection "1; mode=block";

# 禁用内容类型推断
add_header X-Content-Type-Options "nosniff";

# CSP策略
add_header Content-Security-Policy "default-src 'self';";

# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

限制访问

nginx

# 按IP限制访问
location /admin {
    allow 192.168.1.0/24;
    deny all;
}

# 限制连接速率
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

server {
    location /login {
        limit_req zone=one burst=5;
    }
}

十四、Nginx 高级特性

1. 重写与重定向

nginx

# 永久重定向
rewrite ^/old-url$ /new-url permanent;

# 临时重定向
rewrite ^/temp-url$ /new-url redirect;

# 条件重写
if ($http_host = "old.example.com") {
    rewrite ^(.*)$ http://new.example.com$1 permanent;
}

2. 地图模块

nginx

map $http_user_agent $is_mobile {
    default 0;
    "~*android|iphone" 1;
}

server {
    location / {
        if ($is_mobile) {
            rewrite ^ /mobile last;
        }
    }
}

3. 分片上传

nginx

client_max_body_size 100M;
client_body_buffer_size 1M;
client_body_temp_path /tmp/nginx_upload 1 2;

十五、Nginx 监控与调试

1. 状态监控

启用status模块:

nginx

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

访问输出示例:

Active connections: 3 
server accepts handled requests
 100 100 200 
Reading: 0 Writing: 1 Waiting: 2

2. 调试日志

nginx

error_log /var/log/nginx/error.log debug;

3. 实时调试

# 跟踪Nginx进程
strace -p `cat /var/run/nginx.pid`

# 查看打开的文件
lsof -p `cat /var/run/nginx.pid`

结语

Nginx是一个功能强大且灵活的Web服务器和反向代理服务器。通过本教程,您应该已经掌握了Nginx的基本配置和高级功能。要成为Nginx专家,还需要在实际项目中不断实践和探索。

进一步学习资源

  1. Nginx官方文档
  2. Nginx Wiki
  3. Nginx配置生成器









results matching ""

    No results matching ""