
Nginx 是 VPS 部署中最受欢迎的 Web 服务器——它能以极低的内存占用处理大量并发连接。本指南将介绍如何在 Ubuntu 上搭建完整的生产级 Nginx 环境,涵盖 PHP-FPM server block 配置、WordPress 固定链接支持、gzip 压缩、浏览器缓存响应头,以及通过 Let's Encrypt 获取免费 SSL 证书。
安装 Nginx 与 PHP-FPM
sudo apt update
sudo apt install -y nginx php8.3-fpm php8.3-mysql php8.3-curl \
php8.3-gd php8.3-mbstring php8.3-xml php8.3-zip php8.3-redis
sudo systemctl enable nginx php8.3-fpm
sudo systemctl start nginx php8.3-fpm
通用 PHP 网站的 Server Block 配置
sudo nano /etc/nginx/sites-available/mysite.com
server {
listen 80;
server_name mysite.com www.mysite.com;
root /var/www/mysite.com/public;
index index.php index.html;
access_log /var/log/nginx/mysite.com.access.log;
error_log /var/log/nginx/mysite.com.error.log;
# PHP-FPM
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
}
# Block .htaccess
location ~ /\.ht { deny all; }
# Browser cache for static assets
location ~* \.(jpg|jpeg|png|webp|gif|ico|css|js|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}
sudo ln -s /etc/nginx/sites-available/mysite.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
WordPress 专用 Server Block 配置
server {
listen 80;
server_name wordpress.example.com;
root /var/www/wordpress;
index index.php;
# WordPress permalink support
location / {
try_files $uri $uri/ /index.php?$args;
}
# Deny PHP execution in uploads
location ~* /(?:uploads|files)/.*\.php$ { deny all; }
location ~* \.(txt|log|conf|bak)$ { deny all; }
# PHP-FPM
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
# Long-lived cache for static assets
location ~* \.(css|js|jpg|jpeg|png|webp|gif|ico|svg|woff2|ttf)$ {
expires 1y;
add_header Cache-Control "public, immutable";
log_not_found off;
}
}
逐行解析 Server Block
VPS 上 Nginx 配置的核心是 server block(相当于 Apache 的 VirtualHost)。block 中的每个指令都有明确的职责,彻底理解每一行的含义,能让你更快排查问题、精准调优,而不是盲目复制粘贴。下表列出了 PHP 和 WordPress 网站常用的核心指令。
| 指令 | 作用说明 |
|---|---|
listen 80; | 告知 Nginx 监听 80 端口(HTTP);Certbot 配置 SSL 后会自动添加 443 端口(HTTPS) |
server_name | 指定此 block 处理哪些域名——可填写主域名、www 子域名,或多个域名以空格分隔 |
root | 磁盘上存放网站文件的实际目录,例如 /var/www/mysite.com/public |
index | 请求目录时的默认文件——PHP 网站中 index.php 必须排在最前面 |
try_files | 按顺序查找文件,若均不存在则回退到 index.php——伪静态 URL 的核心机制 |
fastcgi_pass | 通过 Unix socket 将 .php 文件转交给 PHP-FPM 处理 |
当请求到达时,Nginx 找到 server_name 匹配的 block,以 root 为基础定位文件。静态文件(图片、CSS、JS)由 Nginx 直接返回,而 .php 文件则通过 fastcgi_pass 转交给 PHP-FPM 处理,再将结果回传给用户。这种职责分离正是 Nginx 提供静态资源速度极快的原因——它只在必要时才唤醒 PHP。
配置 WordPress 固定链接与伪静态 URL
将 WordPress 迁移到 Nginx 时最常见的问题是:首页正常,但其他所有页面都返回 404。原因在于 Nginx 没有 Apache 那样的 .htaccess 文件,无法自动识别"文章名称"格式的固定链接(例如 /category/my-post/)。你需要手动告知 Nginx,使用 try_files 将找不到对应文件的请求转发给 index.php,由 WordPress 负责路由处理。
# The block that makes permalinks work
location / {
try_files $uri $uri/ /index.php?$args;
}
这段配置的含义是:先尝试精确匹配 URI($uri),再尝试将其作为目录($uri/),若仍找不到,则将请求连同原始查询字符串(?$args)一起转交给 index.php。之后在 WordPress > 设置 > 固定链接 中选择"文章名",点击保存即可——无需额外的重写文件。
如果你运行 WordPress 多站点(子目录模式),需要添加以下规则来支持子站结构:
# For WordPress Multisite (subdirectory)
if (!-e $request_filename) {
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
rewrite ^(/[^/]+)?(/wp-.*) $2 last;
rewrite ^(/[^/]+)?(/.*\.php) $2 last;
}
每次修改配置后,务必先运行 sudo nginx -t 验证语法再重载——否则将含有错误的配置重载到线上,整个网站将直接宕机。
启用 Gzip 压缩
在 /etc/nginx/nginx.conf 的 http { } 块中添加以下配置:
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 256;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/json
application/xml
image/svg+xml
font/woff2;
开启 gzip 后,HTML、CSS 和 JavaScript 在发送到浏览器之前会被压缩 60-80%,页面加载速度明显提升——在移动网络下尤为显著。gzip_comp_level 设为 6 是压缩率与 CPU 消耗之间的最佳平衡点,调得更高只会多耗 CPU 而收益递减。gzip_min_length 256 用于避免对极小的文件做无谓压缩。
启用浏览器缓存与设置 client_max_body_size
除了 gzip,在 WordPress VPS 上还有两个配置不可忽略:静态文件的缓存响应头以及提高最大上传大小限制。Nginx 默认将请求体限制为 1 MB,这会导致无法上传大型图片或插件,并触发 413 Request Entity Too Large 错误。
# Set in server { } or http { }
# Raise max upload size to 64 MB
client_max_body_size 64M;
# Browser cache for static files (1-year client-side cache)
location ~* \.(css|js|jpg|jpeg|png|webp|gif|ico|svg|woff2|ttf)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
log_not_found off;
}
expires 1y 配合 Cache-Control "public, immutable",可让浏览器将静态文件缓存长达一年,回访用户无需重新下载,既减轻服务器负担,又让页面秒速呈现。对于 WordPress,需将 client_max_body_size 设置为与 php.ini 中 upload_max_filesize 和 post_max_size 一致的值,否则较小的那个值将成为实际限制。
小贴士:如果想让 WordPress 达到静态网站级别的速度,可以使用 Nginx FastCGI 缓存(fastcgi_cache_path)实现全页缓存。但对大多数网站而言,浏览器缓存搭配 WP Super Cache 等缓存插件已经完全足够。
通过 Let's Encrypt(Certbot)添加 SSL
# Install certbot
sudo apt install -y certbot python3-certbot-nginx
# Obtain certificate (Certbot auto-edits your Nginx config)
sudo certbot --nginx -d mysite.com -d www.mysite.com
# Verify auto-renewal timer
sudo systemctl status certbot.timer
验证 SSL:安装完成后,运行 sudo nginx -t,再通过 SSL 检测工具 测试证书,确认一切配置正确。
安全响应头
在 server block 中添加以下配置,可提升安全评分:
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
调优 PHP-FPM 进程池
sudo nano /etc/php/8.3/fpm/pool.d/www.conf
; Tune based on available RAM
pm = dynamic
pm.max_children = 20
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 8
pm.max_requests = 500
sudo systemctl restart php8.3-fpm
经验参考:pm.max_children 建议设为(总内存 - 512 MB 系统开销)/ 单个 PHP 进程内存。每个 PHP-FPM worker 通常占用 30-50 MB,因此 2 GB VPS 可安全设置 20-30 个子进程。
使用 nginx -t 测试配置、重载服务及常见问题排查
每次重载前,务必先用 nginx -t 测试配置——它会在不影响正在运行的网站的情况下验证所有语法。成功时会输出 syntax is ok 和 test is successful,确认无误后再执行重载。与重启不同,重载会在不中断现有连接的情况下加载新配置,网站不会有任何中断。
# 1. Test the syntax of all config files
sudo nginx -t
# 2. If it passes, reload without dropping connections
sudo systemctl reload nginx
# 3. Watch the error log in real time when debugging
sudo tail -f /var/log/nginx/error.log
# 4. Check service status
sudo systemctl status nginx php8.3-fpm
在实际 VPS 上配置 Nginx 时,你会反复遇到同一批问题。下表列出了最常见的错误及针对性解决方案:
| 症状 / 错误 | 原因与解决方法 |
|---|---|
| 502 Bad Gateway | PHP-FPM 未运行或 socket 路径错误。确认 fastcgi_pass 与实际 socket(php8.3-fpm.sock)一致,并运行 systemctl status php8.3-fpm 检查 |
| 除首页外所有页面 404 | WordPress location / 块中缺少 try_files $uri $uri/ /index.php?$args; |
| 413 Request Entity Too Large | 上传文件超过默认 1 MB 限制。添加 client_max_body_size 64M; |
| 403 Forbidden | 文件权限不正确。将所有者设为 www-data,目录权限 755,文件权限 644 |
| .php 文件被下载而非执行 | 缺少 location ~ \.php$ 块或未安装 PHP-FPM。检查配置并安装 php-fpm |
排查问题最好的习惯是先看错误日志。Nginx 的真实原因记录在 /var/log/nginx/error.log,PHP-FPM 的记录在 /var/log/php8.3-fpm.log。不看日志就猜通常只会浪费时间。VPS 拥有完整的 root 权限,可以自由查看这些日志——而共享主机往往将其锁定。
常见问题解答
Nginx 与 Apache 有什么区别?VPS 上应该选哪个?
Nginx 采用事件驱动架构,能以极低的内存占用处理大量并发连接,非常适合资源有限的 VPS 实例和高流量网站。Apache 在 .htaccess 和模块方面更灵活,但随着连接数增加,内存消耗也会增加。对于运行 PHP/WordPress 的 VPS,我们推荐使用 Nginx + PHP-FPM,因为它具有更好的性能与内存比。
需要单独安装 PHP-FPM 吗?
是的。Nginx 不像 Apache 通过 mod_php 自行处理 PHP,因此需要单独安装 php-fpm,再让 Nginx 通过 fastcgi_pass 将 .php 文件转交给它处理。这种分离实际上是一种优势——你可以独立调优 PHP-FPM 进程池,更有效地管理资源。
为什么修改配置后网站没有变化?
最常见的原因是没有重载 Nginx。请始终运行 sudo nginx -t && sudo systemctl reload nginx。另一个原因是浏览器缓存了旧文件——试试无痕模式或清除缓存。如果使用了 WordPress 缓存插件,也别忘了清除插件缓存。
WordPress + Nginx 需要多大的 VPS?
一个流量适中的 WordPress 网站在 2 GB 内存或更大的 VPS 上运行非常流畅,因为 Nginx + PHP-FPM 的内存效率很高。如果你刚刚起步或运营小型网站,AsiaGB 的 Ubuntu VPS 从每月 500 泰铢起,提供完整 root 访问权限,足以安装 Nginx、PHP-FPM 和 WordPress 全套环境。
需要完整控制 Nginx 的 VPS?
Linux VPS 每月仅需 500 泰铢起,提供完整 Root 访问权限——自由配置 Nginx、PHP-FPM、WordPress 及任意 Web 技术栈。
查看 VPS 方案