Nginx 教程

1. 核心概念

Nginx 是一款高性能的开源 Web 服务器和反向代理服务器,以其稳定性、丰富的功能集、简单的配置和低资源消耗而闻名。它可以用作 HTTP 服务器、反向代理服务器、邮件代理服务器,以及 TCP/UDP 代理服务器。

1.1 基本概念

  • Web 服务器:处理 HTTP 请求,提供静态资源和动态内容。
  • 反向代理:接收客户端请求,转发到后端服务器,然后将响应返回给客户端。
  • 负载均衡:将请求分发到多个后端服务器,提高系统的可用性和性能。
  • 静态资源:直接提供 HTML、CSS、JavaScript、图片等静态文件。
  • 动态内容:通过 FastCGI、uWSGI、SCGI 等协议与后端应用服务器通信,处理动态请求。
  • 虚拟主机:在单个 Nginx 实例上托管多个网站。
  • SSL/TLS 终端:处理 HTTPS 请求,终止 SSL/TLS 连接。

1.2 工作原理

  • 事件驱动架构:使用事件驱动模型和非阻塞 I/O 操作,高效处理并发连接。
  • 多进程模型:主进程负责管理工作进程,工作进程负责处理请求。
  • 配置结构:使用模块化的配置文件,支持灵活的配置。
  • 请求处理:工作进程接收请求,根据配置进行处理,返回响应。

2. 安装配置

2.1 安装 Nginx

2.1.1 Ubuntu/Debian

# 更新软件包列表
apt update

# 安装 Nginx
apt install nginx

# 启动 Nginx
systemctl start nginx

# 启用 Nginx 开机自启
systemctl enable nginx

2.1.2 CentOS/RHEL

# 安装 EPEL 仓库
yum install epel-release

# 安装 Nginx
yum install nginx

# 启动 Nginx
systemctl start nginx

# 启用 Nginx 开机自启
systemctl enable nginx

2.1.3 Windows

Nginx 官方网站 下载 Windows 版本,解压后运行 nginx.exe 即可。

2.2 基本配置

Nginx 的主配置文件通常位于 /etc/nginx/nginx.conf,网站配置文件通常位于 /etc/nginx/sites-available/ 目录,然后通过符号链接到 /etc/nginx/sites-enabled/ 目录。

2.2.1 主配置文件

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

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    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;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

2.2.2 网站配置文件

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

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

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

2.3 配置检查和重载

# 检查配置文件语法
nginx -t

# 重载配置文件
nginx -s reload

# 停止 Nginx
nginx -s stop

# 启动 Nginx
nginx

3. 基本使用

3.1 静态网站托管

配置示例

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

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

3.2 反向代理

配置示例

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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

3.3 负载均衡

配置示例

upstream backend {
    server localhost:3000;
    server localhost:3001;
    server localhost:3002;
}

server {
    listen 80;
    server_name example.com;

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

3.4 SSL/TLS 配置

配置示例

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 on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

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

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

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

4. 高级功能

4.1 缓存配置

配置示例

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 60m;
        proxy_cache_valid 404 1m;
        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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

4.2 Gzip 压缩

配置示例

gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_vary on;
gzip_proxied any;
gzip_min_length 1024;

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

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

4.3 限流配置

配置示例

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

server {
    listen 80;
    server_name example.com;

    location / {
        limit_req zone=mylimit burst=20 nodelay;
        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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

4.4 访问控制

配置示例

server {
    listen 80;
    server_name example.com;

    location /admin {
        allow 192.168.1.0/24;
        deny all;
        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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    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;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

4.5 rewrite 规则

配置示例

server {
    listen 80;
    server_name example.com;

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

5. 最佳实践

5.1 配置最佳实践

  • 使用模块化配置:将不同功能的配置分离到不同的文件中,提高可读性和可维护性。
  • 使用变量:合理使用 Nginx 变量,减少重复配置。
  • 设置合理的超时:根据应用的特性,设置合理的连接超时、代理超时等。
  • 启用压缩:启用 Gzip 压缩,减少传输数据量。
  • 启用缓存:合理配置缓存,提高性能。
  • 设置安全头:配置 HTTP 安全头,提高安全性。
  • 使用 HTTPS:启用 HTTPS,保护数据传输安全。

5.2 性能优化

  • 调整工作进程数:根据 CPU 核心数设置合理的工作进程数。
  • 调整连接数:根据系统资源,设置合理的最大连接数。
  • 启用 sendfile:启用 sendfile 指令,提高文件传输性能。
  • 启用 tcp_nopush:启用 tcp_nopush 指令,提高网络传输效率。
  • 启用 tcp_nodelay:启用 tcp_nodelay 指令,减少网络延迟。
  • 优化缓存:合理配置缓存大小和过期时间。
  • 使用 CDN:对于静态资源,使用 CDN 加速。

5.3 安全最佳实践

  • 更新 Nginx:及时更新 Nginx 到最新版本,修复安全漏洞。
  • 限制访问:使用 allow/deny 指令限制对敏感路径的访问。
  • 配置 SSL/TLS:使用强密码套件,启用 HTTP/2 和 HSTS。
  • 隐藏版本信息:在配置中隐藏 Nginx 版本信息。
  • 设置合理的文件权限:确保配置文件和日志文件的权限合理。
  • 使用防火墙:配置防火墙,限制对 Nginx 端口的访问。
  • 定期备份:定期备份 Nginx 配置文件和证书。

6. 实用应用案例

6.1 企业网站托管

场景:托管企业官网,提供静态内容和动态应用。

配置

# 静态资源配置
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.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_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";

    # 静态资源
    location / {
        root /var/www/example.com;
        index index.html;
        try_files $uri $uri/ @backend;
    }

    # 动态应用
    location @backend {
        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;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffers 16 16k;
        proxy_buffer_size 32k;
        proxy_read_timeout 60;
    }

    # 静态资源缓存
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {
        root /var/www/example.com;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

6.2 API 网关

场景:作为 API 网关,转发请求到不同的后端服务,提供认证、限流等功能。

配置

# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;

# 后端服务上游
upstream auth_service {
    server localhost:8000;
}

upstream user_service {
    server localhost:8001;
}

upstream product_service {
    server localhost:8002;
}

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

server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';

    # 全局配置
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
    add_header Access-Control-Allow-Headers "Content-Type, Authorization";

    # 健康检查
    location /health {
        return 200 'OK';
    }

    # 认证服务
    location /api/auth/ {
        limit_req zone=api_limit burst=200 nodelay;
        proxy_pass http://auth_service;
        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 /api/users/ {
        limit_req zone=api_limit burst=200 nodelay;
        proxy_pass http://user_service;
        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 /api/products/ {
        limit_req zone=api_limit burst=200 nodelay;
        proxy_pass http://product_service;
        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;
    }
}

6.3 微服务架构中的反向代理

场景:在微服务架构中,作为前端反向代理,将请求转发到不同的微服务。

配置

# 微服务上游
upstream frontend {
    server localhost:3000;
}

upstream api_gateway {
    server localhost:8080;
}

upstream admin_service {
    server localhost:9000;
}

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

server {
    listen 443 ssl http2;
    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_prefer_server_ciphers on;

    # 前端应用
    location / {
        proxy_pass http://frontend;
        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_buffers 16 16k;
        proxy_buffer_size 32k;
        proxy_read_timeout 60;
    }

    # API 网关
    location /api/ {
        proxy_pass http://api_gateway;
        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_buffers 16 16k;
        proxy_buffer_size 32k;
        proxy_read_timeout 60;
    }

    # 管理后台
    location /admin/ {
        allow 192.168.1.0/24;
        deny all;
        proxy_pass http://admin_service;
        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_buffers 16 16k;
        proxy_buffer_size 32k;
        proxy_read_timeout 60;
    }

    # 静态资源
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {
        proxy_pass http://frontend;
        proxy_cache_valid 200 30d;
        add_header Cache-Control "public, immutable";
    }
}

7. 总结

Nginx 是一款功能强大、性能优秀的 Web 服务器和反向代理服务器,广泛应用于各种场景,从简单的静态网站托管到复杂的微服务架构中的 API 网关。

通过本教程的学习,您应该已经掌握了 Nginx 的核心概念、安装配置、基本使用、高级功能和最佳实践。在实际应用中,您可以根据具体的需求,灵活配置 Nginx,以满足不同场景的要求。

7.1 核心优势

  • 高性能:事件驱动架构和非阻塞 I/O 操作,高效处理并发连接。
  • 稳定性:经过多年的发展和验证,具有良好的稳定性和可靠性。
  • 功能丰富:支持反向代理、负载均衡、SSL/TLS 终端、缓存、限流等多种功能。
  • 配置灵活:模块化的配置文件,支持灵活的配置。
  • 低资源消耗:相比其他 Web 服务器,资源消耗更低。
  • 开源免费:开源软件,免费使用。

7.2 应用前景

随着互联网的发展和技术的进步,Nginx 的应用前景越来越广阔:

  • 云原生环境:在云原生环境中,Nginx 可以作为 ingress controller,管理 Kubernetes 集群的入站流量。
  • 微服务架构:在微服务架构中,Nginx 可以作为 API 网关,管理服务间的通信。
  • 边缘计算:在边缘计算场景中,Nginx 可以部署在边缘节点,提供低延迟的服务。
  • IoT 设备:在 IoT 设备中,Nginx 可以作为轻量级的 Web 服务器和代理服务器。
  • 5G 网络:随着 5G 网络的普及,Nginx 可以更好地支持高带宽、低延迟的应用场景。

通过不断学习和实践 Nginx 的功能和最佳实践,您可以充分发挥 Nginx 的优势,构建高性能、可靠、安全的 Web 服务和应用架构。

« 上一篇 Alertmanager 教程 下一篇 » Apache HTTP Server 教程