Nginx 的安装与卸载

安装

  1. Ubuntu/Debian

    sudo apt update
    sudo apt install nginx
    sudo systemctl start nginx
    sudo systemctl enable nginx
  2. CentOS/RHEL

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

卸载

  1. Ubuntu/Debian

    sudo systemctl stop nginx
    sudo apt purge nginx nginx-common
    sudo apt autoremove
  2. CentOS/RHEL

    sudo systemctl stop nginx
    sudo yum remove nginx
    sudo rm -rf /etc/nginx /var/log/nginx

配置优化与企业实战场景

1. 基础配置优化

  • 工作进程与连接数

    worker_processes auto;  # 与 CPU 核心数匹配
    events {
        worker_connections 1024;  # 单进程最大连接数
        use epoll;  # 高效事件模型(Linux)
    }
  • 缓冲区与超时

    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    keepalive_timeout 65;

2. Location 匹配规则

  • 精确匹配

    location = /login {
        # 仅匹配 /login
    }
  • 前缀匹配

    location /static/ {
        # 匹配 /static/ 开头的路径
    }
  • 正则匹配

    location ~ \.(jpg|png)$ {
        # 匹配所有 .jpg 或 .png 文件
    }

3. 动静分离

server {
 location / {
 proxy_pass http://dynamic_backend; # 动态请求
 }

 location ~* \.(jpg|css|js)$ {
 root /data/static; # 静态资源目录
 expires 30d; # 缓存过期时间
 }
}

4. 反向代理与负载均衡

  • 反向代理

    location / {
     proxy_pass http://backend_server;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
    }
  • 负载均衡(轮询)

    upstream backend {
     server 192.168.1.101;
     server 192.168.1.102;
     server 192.168.1.103;
    }
    
    server {
     location / {
     proxy_pass http://backend;
     }
    }
  • 权重分配

    upstream backend {
     server 192.168.1.101 weight=3; # 60% 流量
     server 192.168.1.102 weight=2; # 40% 流量
    }

5. 安全优化

  • 隐藏版本号

    server_tokens off;
  • 限制请求方法

    if ($request_method !~ ^(GET|POST)$) {
     return 444; # 非标准状态码,直接断开连接
    }

企业实战场景

  1. 高并发场景

    • 启用 gzip 压缩
    • 使用 HTTP/2
    • 配置缓存(如 proxy_cache
  2. HTTPS 配置

    server {
     listen 443 ssl;
     ssl_certificate /path/to/cert.pem;
     ssl_certificate_key /path/to/key.pem;
     # 强制重定向 HTTP 到 HTTPS
     if ($scheme = http) {
     return 301 https://$host$request_uri;
     }
    }
  3. 日志切割

    # 使用 logrotate(默认配置位于 /etc/logrotate.d/nginx)
    /var/log/nginx/*.log {
     daily
     rotate 30
     compress
     missingok
     notifempty
    }

总结

Nginx 的灵活配置使其适用于多种场景:

  • 静态资源加速:通过 expiresgzip 优化
  • 动态请求分发:反向代理 + 负载均衡
  • 安全防护:隐藏信息、限制请求方法
  • 高可用架构:结合 Keepalived 实现 VIP 漂移