参考资料

  1. Nginx的常见错误及解决方案
  2. Nginx Keepalived配置详细说明以及案例
  3. Nginx集群负载(基于LVS和Keepalived)搭建详细说明以及案例
  4. Nginx配置修改工具Ansible详细说明以及案例
  5. Nginx stream模块详细说明以及案例
  6. Nginx进程配置指令详解
  7. nginx 配置代理
  8. Nginx TCP/UDP代理详细说明以及案例

Nginx 应用场景及配置教程

1. 静态文件服务

应用场景

  • 高效托管 HTML、CSS、JS、图片等静态资源

  • 适用于 CDN、前端项目部署

配置示例

server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;  # 静态文件目录
        index index.html;    # 默认首页
    }
}

2. 反向代理

应用场景

  • 隐藏后端服务器(如 Node.js、Java、Python 应用)

  • 提供缓存、负载均衡

配置示例

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

3. 负载均衡

应用场景

  • 分发请求到多个后端服务器(如集群部署)

  • 支持轮询、权重、IP 哈希等策略

配置示例

upstream backend_servers {
    server 192.168.1.10:8080 weight=3;  # 权重 3
    server 192.168.1.11:8080;           # 默认权重 1
    server 192.168.1.12:8080 backup;    # 备用服务器
}

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

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

4. HTTPS 加密(SSL/TLS)

应用场景

  • 加密 HTTP 流量,提升安全性

  • 适用于 Web、API、支付等场景

配置示例

server {
    listen 443 ssl;
    server_name secure.example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

# 强制 HTTP 跳转 HTTPS
server {
    listen 80;
    server_name secure.example.com;
    return 301 https://$host$request_uri;
}

5. 缓存加速

应用场景

  • 缓存动态内容(如 API 响应)

  • 减少后端服务器压力

配置示例

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

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

    location / {
        proxy_cache my_cache;
        proxy_pass http://127.0.0.1:3000;
        proxy_cache_valid 200 302 10m;  # 缓存 200/302 响应 10 分钟
    }
}

6. 访问控制(IP 限制)

应用场景

  • 限制特定 IP 访问(如管理后台)

  • 防止恶意请求

配置示例

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

    location / {
        allow 192.168.1.100;  # 允许的 IP
        deny all;             # 拒绝其他所有 IP
        proxy_pass http://127.0.0.1:3000;
    }
}

7. 日志管理

应用场景

  • 记录访问日志、错误日志

  • 分析流量、排查问题

配置示例

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;
    error_log /var/log/nginx/error.log warn;
}

8. 常用命令

# 启动 Nginx
sudo systemctl start nginx

# 停止 Nginx
sudo systemctl stop nginx

# 重新加载配置(不重启)
sudo nginx -s reload

# 测试配置语法
sudo nginx -t

# 查看运行状态
sudo systemctl status nginx

总结

Nginx