Nginx 教程

纯干货教学,从零开始学习 Nginx

Nginx 集成应用

掌握 Nginx 与各种技术和框架的集成方法

Nginx 与 PHP 集成

使用 PHP-FPM

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php index.html;
    
    # 处理 PHP 文件
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
    }
    
    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }
}

安装 PHP-FPM

# Ubuntu/Debian
sudo apt update
sudo apt install php-fpm php-mysql php-cli php-mbstring php-curl php-gd php-xml

# CentOS/RHEL
sudo yum install php-fpm php-mysqlnd php-cli php-mbstring php-curl php-gd php-xml

# 启动 PHP-FPM
sudo systemctl start php-fpm
sudo systemctl enable php-fpm

Nginx 与 Node.js 集成

作为反向代理

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_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_cache_bypass $http_upgrade;
    }
    
    # 静态文件直接处理
    location /static/ {
        root /var/www/node-app;
        expires 30d;
    }
}

使用 PM2 管理 Node.js 进程

# 安装 PM2
npm install -g pm2

# 启动应用
pm start

# 或使用 PM2 启动
pm run build
pm run start:prod

# 查看进程状态
pm list

# 重启应用
pm restart

# 停止应用
npm stop

Nginx 与 Python 集成

与 Django 集成

server {
    listen 80;
    server_name example.com;
    
    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }
    
    # 静态文件
    location /static/ {
        root /var/www/django-app;
        expires 30d;
    }
    
    location /media/ {
        root /var/www/django-app;
        expires 30d;
    }
    
    # 动态内容
    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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

与 Flask 集成

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://localhost:5000;
        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 /static/ {
        root /var/www/flask-app;
        expires 30d;
    }
}

Nginx 与 Java 集成

与 Tomcat 集成

upstream tomcat_servers {
    server localhost:8080;
    # 可以添加多个 Tomcat 服务器实现负载均衡
    # server localhost:8081;
    # server localhost:8082;
}

server {
    listen 80;
    server_name example.com;
    
    # 静态文件
    location /static/ {
        root /var/www/java-app;
        expires 30d;
    }
    
    # 动态内容
    location / {
        proxy_pass http://tomcat_servers;
        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;
        
        # Tomcat 特定配置
        proxy_redirect http://tomcat_servers/ /;
        proxy_connect_timeout 60;
        proxy_send_timeout 60;
        proxy_read_timeout 60;
    }
}

与 Spring Boot 集成

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://localhost: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;
    }
    
    # 静态文件
    location /static/ {
        root /var/www/spring-app;
        expires 30d;
    }
}

Nginx 与数据库集成

与 MySQL/MariaDB 集成

Nginx 本身不直接与数据库集成,但可以通过反向代理和缓存来优化数据库应用:

# 配置代理缓存
http {
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=db_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    server {
        listen 80;
        server_name example.com;
        
        location /api {
            proxy_pass http://localhost:8080;
            proxy_cache db_cache;
            proxy_cache_valid 200 302 5m;
            proxy_cache_valid 404 1m;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            add_header X-Cache-Status $upstream_cache_status;
        }
    }
}

与 Redis 集成

使用 Nginx + Redis 实现缓存和会话共享:

# 安装 ngx_http_redis 模块
# 重新编译 Nginx
./configure --add-module=../ngx_http_redis
make && make install

# 配置 Redis 缓存
http {
    upstream redis_backend {
        server 127.0.0.1:6379;
        keepalive 1024;
    }
    
    server {
        listen 80;
        server_name example.com;
        
        location /redis {
            set $redis_key $arg_key;
            redis_pass redis_backend;
            default_type text/plain;
            error_page 404 = /redis_error;
        }
        
        location = /redis_error {
            return 404 "Key not found";
        }
    }
}

Nginx 与 Docker 集成

使用 Docker 运行 Nginx

# 创建 Dockerfile
FROM nginx:latest

# 复制配置文件
COPY nginx.conf /etc/nginx/nginx.conf
COPY default.conf /etc/nginx/conf.d/default.conf

# 复制网站文件
COPY html/ /usr/share/nginx/html/

# 暴露端口
EXPOSE 80 443

# 启动 Nginx
CMD ["nginx", "-g", "daemon off;"]

使用 Docker Compose

# docker-compose.yml
version: '3'
services:
  nginx:
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./html:/usr/share/nginx/html
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./conf.d:/etc/nginx/conf.d
    depends_on:
      - app
  
  app:
    build: ./app
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production

# 启动服务
docker-compose up -d

# 查看服务状态
docker-compose ps

# 停止服务
docker-compose down

Nginx 与 CDN 集成

配置 CDN 源站

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    
    # 允许 CDN 访问
    location / {
        # 验证 CDN 回源请求
        if ($http_x_forwarded_for !~* "192.168.1.0/24") {
            # 可以添加 CDN 提供商的 IP 段
        }
        
        # 静态文件
        location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ {
            expires 30d;
            add_header Cache-Control "public, max-age=2592000";
            add_header Access-Control-Allow-Origin *;
        }
    }
}

配置 CDN 缓存

在 CDN 提供商的控制台中配置:

  1. 添加加速域名
  2. 设置源站地址为你的 Nginx 服务器
  3. 配置缓存规则,针对静态文件设置较长的缓存时间
  4. 配置 HTTPS 证书
  5. 启用 HTTP/2 和 Brotli 压缩

Nginx 与监控工具集成

与 Prometheus + Grafana 集成

# 安装 nginx-prometheus-exporter
git clone https://github.com/nginxinc/nginx-prometheus-exporter.git
cd nginx-prometheus-exporter
make build

# 运行 exporter
./nginx-prometheus-exporter -nginx.scrape-uri=http://localhost/nginx_status

# 配置 Prometheus 抓取
sudo nano /etc/prometheus/prometheus.yml
# 添加以下内容
scrape_configs:
  - job_name: 'nginx'
    static_configs:
      - targets: ['localhost:9113']

# 启动 Prometheus 和 Grafana
sudo systemctl start prometheus
sudo systemctl start grafana-server

与 ELK Stack 集成

# 安装 Filebeat
download_filebeat() {
    local version="7.17.0"
    local os="linux"
    local arch="x86_64"
    local url="https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-${version}-${os}-${arch}.tar.gz"
    
    wget "$url" -O filebeat-${version}-${os}-${arch}.tar.gz
    tar xzf filebeat-${version}-${os}-${arch}.tar.gz
    cd filebeat-${version}-${os}-${arch}
}

download_filebeat

# 配置 Filebeat
sudo nano /etc/filebeat/filebeat.yml
# 添加以下内容
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/nginx/access.log
    - /var/log/nginx/error.log

output.elasticsearch:
  hosts: ["localhost:9200"]

# 启动 Filebeat
sudo systemctl start filebeat
sudo systemctl enable filebeat

实践练习

练习1:Nginx 与 PHP 集成

  1. 安装 Nginx 和 PHP-FPM
  2. 创建一个简单的 PHP 脚本:
  3. 配置 Nginx 处理 PHP 文件
  4. 测试访问 PHP 页面

练习2:Nginx 与 Node.js 集成

  1. 安装 Node.js 和 npm
  2. 创建一个简单的 Express 应用
  3. 配置 Nginx 作为反向代理
  4. 测试访问 Node.js 应用

练习3:Nginx 与 Docker 集成

  1. 安装 Docker
  2. 创建 Dockerfile 和 docker-compose.yml
  3. 构建并运行容器
  4. 测试访问容器中的 Nginx 服务

常见问题解答

Q: Nginx 与 Apache 可以共存吗?

A: 可以,只需要配置不同的端口即可。例如,Nginx 监听 80 端口,Apache 监听 8080 端口,然后通过 Nginx 反向代理到 Apache。

Q: 如何处理 Nginx 与后端服务的会话共享?

A: 可以使用以下方法:

  • 使用 Redis 或 Memcached 存储会话
  • 配置 Nginx 的 IP 哈希负载均衡算法
  • 使用粘性会话(sticky session)

Q: 如何优化 Nginx 与后端服务的通信?

A: 可以采取以下措施:

  • 启用 keepalive 连接
  • 调整代理超时设置
  • 启用代理缓存
  • 优化后端服务性能

Q: 如何配置 Nginx 处理WebSocket 连接?

A: 需要在 Nginx 配置中添加以下内容:

location /ws {
    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    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 86400;
}