Skip to content

Nginx安装与配置

Nginx简介

Nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。

Nginx安装

Ubuntu/Debian

bash
# 安装
sudo apt update
sudo apt install -y nginx

# 启动
sudo systemctl start nginx
sudo systemctl enable nginx

# 验证
sudo systemctl status nginx
curl http://localhost

CentOS/RHEL

bash
# 安装
sudo yum install -y nginx

# 启动
sudo systemctl start nginx
sudo systemctl enable nginx

# 配置防火墙
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

# 验证
sudo systemctl status nginx
curl http://localhost

编译安装

bash
# 安装依赖
sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

# 下载源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 编译配置
./configure \
    --prefix=/usr/local/nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_gzip_static_module

# 编译安装
make
sudo make install

# 启动
sudo /usr/local/nginx/sbin/nginx

基本配置

配置文件结构

nginx
# 主配置文件:/etc/nginx/nginx.conf

user www-data;
worker_processes auto;
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;
    error_log /var/log/nginx/error.log;

    # 基本设置
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_types text/plain text/css application/json application/javascript;

    # 虚拟主机配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

静态网站配置

nginx
# /etc/nginx/conf.d/mysite.conf

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

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # 日志
    access_log /var/log/nginx/mysite_access.log;
    error_log /var/log/nginx/mysite_error.log;
}

反向代理配置

nginx
server {
    listen 80;
    server_name api.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;

        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

负载均衡配置

nginx
# 定义上游服务器组
upstream backend {
    # 负载均衡策略
    # 1. 轮询(默认)
    # 2. least_conn - 最少连接
    # 3. ip_hash - IP哈希
    # 4. random - 随机
    
    least_conn;
    
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 weight=1;
    server 192.168.1.13:8080 backup;  # 备用服务器
}

server {
    listen 80;
    server_name lb.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;
    }
}

HTTPS配置

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

    # SSL证书
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    # SSL配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 强制HTTPS
    add_header Strict-Transport-Security "max-age=31536000" always;

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

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

Let's Encrypt免费SSL证书

bash
# 安装certbot
sudo apt install -y certbot python3-certbot-nginx

# 获取证书
sudo certbot --nginx -d example.com -d www.example.com

# 自动续期
sudo certbot renew --dry-run

# 添加定时任务
sudo crontab -e
# 每天凌晨2点检查续期
0 2 * * * certbot renew --quiet

高级配置

限流配置

nginx
# 限制请求速率
http {
    # 定义限流区域(每秒10个请求)
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
    
    server {
        location /api/ {
            limit_req zone=mylimit burst=20 nodelay;
            proxy_pass http://backend;
        }
    }
}

# 限制连接数
http {
    # 每个IP最多5个连接
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    
    server {
        location / {
            limit_conn conn_limit 5;
        }
    }
}

缓存配置

nginx
# 配置缓存路径
http {
    proxy_cache_path /var/cache/nginx 
                     levels=1:2 
                     keys_zone=my_cache:10m 
                     max_size=1g 
                     inactive=60m;

    server {
        location / {
            proxy_cache my_cache;
            proxy_cache_key $scheme$proxy_host$request_uri;
            proxy_cache_valid 200 60m;
            proxy_cache_valid 404 10m;
            
            # 缓存状态头
            add_header X-Cache-Status $upstream_cache_status;
            
            proxy_pass http://backend;
        }
    }
}

跨域配置

nginx
location /api/ {
    # 允许的域名
    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';
    
    # 预检请求缓存时间
    add_header 'Access-Control-Max-Age' 86400;
    
    # OPTIONS请求直接返回
    if ($request_method = 'OPTIONS') {
        return 204;
    }
    
    proxy_pass http://backend;
}

WebSocket配置

nginx
location /ws/ {
    proxy_pass http://backend;
    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_read_timeout 3600s;
    proxy_send_timeout 3600s;
}

常用命令

bash
# 测试配置文件
sudo nginx -t

# 重新加载配置
sudo nginx -s reload

# 停止
sudo nginx -s stop      # 快速停止
sudo nginx -s quit      # 优雅停止

# 查看版本
nginx -v
nginx -V  # 查看编译参数

# 查看进程
ps aux | grep nginx

# 查看端口
sudo netstat -tunlp | grep nginx
sudo ss -tunlp | grep nginx

性能优化

调优参数

nginx
# nginx.conf

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

# 每个工作进程的最大连接数
events {
    worker_connections 4096;
    use epoll;  # Linux使用epoll
}

http {
    # 开启高效文件传输
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    
    # 客户端请求超时
    client_body_timeout 12;
    client_header_timeout 12;
    
    # 长连接超时
    keepalive_timeout 15;
    keepalive_requests 100;
    
    # 缓冲区大小
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 4 8k;
    
    # Gzip压缩
    gzip on;
    gzip_comp_level 5;
    gzip_min_length 256;
    gzip_types text/plain text/css application/json application/javascript;
    
    # 缓存文件描述符
    open_file_cache max=10000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
}

日志管理

日志格式

nginx
# 自定义日志格式
log_format custom '$remote_addr - $remote_user [$time_local] '
                  '"$request" $status $body_bytes_sent '
                  '"$http_referer" "$http_user_agent" '
                  '$request_time $upstream_response_time';

access_log /var/log/nginx/access.log custom;

日志切割

bash
# 使用logrotate
sudo vim /etc/logrotate.d/nginx

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

监控

启用status模块

nginx
server {
    listen 8080;
    server_name localhost;
    
    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

访问 http://localhost:8080/nginx_status 查看状态。

故障排查

bash
# 查看错误日志
sudo tail -f /var/log/nginx/error.log

# 检查配置语法
sudo nginx -t

# 查看进程
ps aux | grep nginx

# 查看端口占用
sudo lsof -i:80

# 测试连接
curl -I http://localhost

💡 提示

这是一个demo文档,欢迎补充更多Nginx相关内容。

基于 VitePress 构建