Ubuntu服务器多站点下Nginx配置PHP网站友好URL重写方法
Nginx为多站点PHP配置友好URL重写方案
前提准备
- 确保Nginx已启用rewrite模块:执行
nginx -V,输出中包含--with-http_rewrite_module即表示启用(Ubuntu默认安装已包含)。 - 每个站点拥有独立的Nginx配置文件(通常位于
/etc/nginx/sites-available/,通过软链到/etc/nginx/sites-enabled/启用)。 - 已配置好PHP-FPM与Nginx的联动(基础的PHP请求处理规则)。
核心配置方案
1. 通用单入口重写(适配自定义框架/单入口程序)
大部分PHP框架或自定义单入口程序,需要将所有非静态资源请求转发到index.php,同时保留原请求参数。
在站点的server块中添加:
server { listen 80; server_name your-domain.com; # 替换为你的站点域名 root /var/www/your-site; # 替换为站点根目录 index index.php index.html; # 友好URL重写规则 location / { try_files $uri $uri/ /index.php?$args; } # PHP请求处理 location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 替换为对应PHP版本的socket路径 } }
说明:
try_files $uri $uri/ /index.php?$args:优先访问真实存在的文件/目录,若不存在则将请求转发到index.php并保留原查询参数。- 替换
your-domain.com、站点根目录、PHP-FPM socket路径为实际值。
2. 自定义规则重写(适配特定URL格式)
如果需要将特定格式的URL映射到PHP参数(如/post/123 → index.php?post_id=123),可使用rewrite指令:
server { # 基础配置同上... # 自定义重写规则:匹配/post/数字格式的URL rewrite ^/post/(\d+)$ /index.php?post_id=$1 last; # 通用单入口兜底(可选,若还有其他路由需求) location / { try_files $uri $uri/ /index.php?$args; } # PHP处理规则同上... }
说明:
^/post/(\d+)$:正则匹配以/post/开头、后跟数字的URL,(\d+)为捕获组,对应$1。last:表示执行完该重写规则后,停止当前location的处理,重新匹配新的URL规则。
3. CMS专属配置(以WordPress为例)
WordPress等CMS的友好URL(固定链接)配置,核心规则与通用单入口一致,需额外添加静态资源缓存与敏感文件防护:
server { listen 80; server_name wp-domain.com; root /var/www/wordpress; index index.php index.html; # WordPress友好URL规则 location / { try_files $uri $uri/ /index.php?$args; } # 静态资源缓存优化 location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ { expires 30d; add_header Cache-Control "public, no-transform"; access_log off; } # 禁止访问敏感文件 location ~* (wp-config.php|readme\.md|license\.txt) { deny all; } # PHP处理规则 location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.2-fpm.sock; } }
多站点配置注意事项
- 每个站点的
server块必须明确server_name,避免域名解析冲突。 - 不同站点的
root目录需独立,确保文件隔离。 - 修改配置后,务必执行
nginx -t检查配置语法,无错误后执行systemctl reload nginx使配置生效。 - 确保Nginx进程用户(默认
www-data)拥有站点目录的读取权限,可执行chown -R www-data:www-data /var/www/your-site调整权限。
调试技巧
若重写规则不生效,可开启rewrite日志排查:
server { # 其他配置... rewrite_log on; error_log /var/log/nginx/your-site-rewrite.log notice; }
调试完成后记得关闭rewrite_log,避免日志占用过多磁盘空间。
内容的提问来源于stack exchange,提问作者Phạm Hữu Thành
相关产品推荐
相关产品推荐

