VPS上高级Nginx配置虚拟主机SSL Gzip

目录

为什么需要高级Nginx配置

Nginx(读作"Engine-X")是2026年全球最受欢迎的Web服务器,用于超过34%的网站。其事件驱动的非阻塞I/O架构使其能够以极低的内存占用处理数万个并发连接。

虽然默认安装就能运行,但生产VPS需要针对性能、安全性和可靠性进行专门调优。

配置项默认值优化后
工作进程数1= CPU核心数(auto)
工作连接数7681024–65535
Gzip压缩关闭开启,级别5
SSL协议TLSv1 TLSv1.1 TLSv1.2仅TLSv1.2 TLSv1.3
安全标头无HSTS, X-Frame-Options等
速率限制无每IP限制请求/秒
FastCGI缓存关闭WordPress专用缓存

安装与文件结构

在Ubuntu 22.04/24.04 LTS上安装Nginx:

sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

关键文件位置

优化后的nginx.conf

user www-data;
worker_processes auto;    # 自动使用所有CPU核心
pid /run/nginx.pid;

events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    server_tokens off;    # 隐藏Nginx版本号

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

    gzip on;    # 详见Gzip章节

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

提示:server_tokens off隐藏HTTP响应头中的Nginx版本号,防止攻击者识别版本并利用对应漏洞。

虚拟主机(服务器块)

Nginx将虚拟主机称为服务器块(Server Block)。通过SNI(服务器名称指示),单个IP地址可以托管多个域名。

创建服务器块

sudo nano /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example.com/public;
    index index.php index.html index.htm;

    # PHP-FPM处理器
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~ /\.ht {
        deny all;
    }

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}
# 启用服务器块
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t        # 测试配置
sudo nginx -s reload # 重新加载

SSL/TLS配置

2026年,SSL对所有生产网站都是必不可少的。使用Let's Encrypt获取免费SSL证书:

安装Certbot

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

加固的SSL配置

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;

    # 仅允许TLS 1.2和1.3
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;

    # OCSP装订
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 1.1.1.1 8.8.8.8 valid=300s;

    # SSL会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
}

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

⚠️ 重要:生产服务器上绝对不要启用TLSv1或TLSv1.1——两者都有已知漏洞。只使用TLSv1.2和TLSv1.3。

Gzip压缩

Gzip可将文本文件大小减少60-80%。在nginx.conf的http {}块中添加:

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;        # 级别1-9(5=CPU与压缩比的平衡)
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;      # 不压缩小于256字节的文件
gzip_types
    application/javascript
    application/json
    application/xml
    font/ttf
    image/svg+xml
    text/css
    text/javascript
    text/plain
    text/xml;

注意:不要对已压缩格式(JPEG、PNG、WebP、ZIP、MP4)使用Gzip——它们不会进一步压缩,只会浪费CPU资源。

安全标头

安全标头可防范常见的Web攻击。在服务器块中添加:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

# HSTS——在SSL正常运行至少一周后启用
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
标头防护对象
X-Frame-Options: SAMEORIGIN点击劫持攻击
X-Content-Type-Options: nosniffMIME类型混淆攻击
Referrer-Policy通过引用头泄露信息
X-XSS-Protection反射型XSS(旧版浏览器)
Strict-Transport-SecuritySSL剥离、中间人攻击
Permissions-Policy未经授权的浏览器API访问

速率限制

速率限制限制单个IP可以发送的请求数量,防止DDoS攻击和暴力破解登录:

# 添加到nginx.conf的http {}块
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
# WordPress登录保护
location = /wp-login.php {
    limit_req zone=login burst=3 nodelay;
    limit_conn addr 3;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}

# API端点
location /api/ {
    limit_req zone=api burst=20 nodelay;
    proxy_pass http://backend;
}

缓存与反向代理

FastCGI缓存将PHP输出存储在磁盘上,使后续请求速度提升10-50倍:

# 添加到http {}块
fastcgi_cache_path /tmp/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
# 在server {}块中
set $skip_cache 0;

# 跳过缓存:POST请求、已登录用户
if ($request_method = POST) { set $skip_cache 1; }
if ($http_cookie ~* "wordpress_logged_in") { set $skip_cache 1; }

location ~ \.php$ {
    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 200 60m;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    add_header X-FastCGI-Cache $upstream_cache_status;
}

Node.js/Python反向代理

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

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

WordPress优化

WordPress在Nginx上需要特殊配置,因为Nginx不支持.htaccess,使用try_files指令处理固定链接:

server {
    listen 443 ssl http2;
    server_name myblog.com www.myblog.com;
    root /var/www/myblog.com/public;
    index index.php;

    # WordPress固定链接处理
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # 阻止敏感文件直接访问
    location ~* /(?:uploads|files)/.*\.php$ { deny all; }
    location = /xmlrpc.php { deny all; }

    # 静态资源浏览器缓存
    location ~* \.(css|js|png|jpg|jpeg|gif|webp|ico|svg|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    location ~ /\.ht { deny all; }
}

测试与调试

每次重新加载Nginx前,始终先测试配置:

# 测试配置语法
sudo nginx -t

# 预期输出:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

# 重新加载而不停止服务
sudo nginx -s reload
# 或
sudo systemctl reload nginx

实时监控日志

# 访问日志
sudo tail -f /var/log/nginx/access.log

# 错误日志(调试问题的关键)
sudo tail -f /var/log/nginx/error.log

生产Nginx配置清单

常见问题

Nginx和Apache有什么区别?应该选哪个?
Nginx采用事件驱动的非阻塞I/O模型,能以极低内存处理数万个并发连接。Apache采用每连接进程/线程模型,高并发时消耗更多内存。对于需要高性能的VPS,Nginx通常是更好的选择,特别是与PHP-FPM和FastCGI缓存结合使用时,非常适合WordPress。
在VPS上运行Nginx需要多少内存?
每个Nginx工作进程大约使用5-15 MB内存。1 GB内存的VPS可以轻松运行Nginx + PHP-FPM + MariaDB。对于高流量WordPress或多域名站点,建议2 GB或更多内存。AsiaGB VPS Thailand起价500泰铢/月,提供SSD存储,99%正常运行时间保障。
如何在重新加载前测试Nginx配置?
运行sudo nginx -t测试所有配置语法。测试通过会显示\"syntax is ok\"和\"test is successful\"。然后使用sudo nginx -s reload应用更改而不停止服务。如果配置有误,Nginx不会重新加载,网站继续正常运行。
Gzip压缩能提升多少网站速度?
Gzip通常可以将HTML、CSS和JavaScript文件大小减少60-80%,显著改善页面加载时间,特别是对网速较慢的用户。对于已压缩格式如JPEG、PNG、WebP等,不需要添加Gzip,因为它们不会进一步压缩,反而浪费CPU资源。
每台Nginx服务器应该添加哪些安全标头?
必要的安全标头包括:X-Frame-Options(防止点击劫持)、X-Content-Type-Options: nosniff(防止MIME类型混淆)、Strict-Transport-Security(强制HTTPS)、Referrer-Policy(控制引用信息)和Permissions-Policy(限制浏览器API访问)。这些标头应使用\"always\"参数确保错误响应时也发送。
Nginx支持.htaccess文件吗?
不,Nginx不支持.htaccess文件。所有配置必须在服务器块文件中进行。对于WordPress,使用try_files $uri $uri/ /index.php?$args;指令替代.htaccess重写规则。这实际上性能更好,因为每次请求不需要检查.htaccess文件是否存在。

需要适合Nginx的VPS?

AsiaGB提供泰国和新加坡VPS,配备快速SSD存储,99%正常运行时间保障,支持Ubuntu 22.04/24.04。立即部署Nginx,快速启动您的项目。

查看VPS套餐 →