Nginx配置伪静态,ThinkPHP/WordPress规则
时间:2026-10-7 07:33 作者:emer 分类: 无
前言
ThinkPHP、WordPress 这些程序,URL 一般都带 index.php 或者 ? 参数,比如 www.example.com/index.php?m=user&a=login。伪静态就是把这种丑陋的 URL 变成好看的,比如 www.example.com/user/login.html。对 SEO 也友好。
什么是伪静态
伪静态就是 Nginx 把好看的 URL 内部重写到真实的 PHP 文件,用户看到的是好看的 URL,实际服务器还是走原来的程序。
通用伪静态规则
大部分 PHP 框架都用这个规则:
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
}
}
意思是:如果请求的文件/目录不存在,就重写到 index.php,把路径作为参数传过去。
ThinkPHP 伪静态规则
ThinkPHP 5/6 版本
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
}
}
完整站点配置:
server {
listen 80;
server_name www.example.com;
root /var/www/thinkphp/public;
index index.php index.html;
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=/$1 last;
}
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
WordPress 伪静态规则
WordPress 的伪静态叫"固定链接",设置成文章名(/%postname%/)就需要 Nginx 重写规则:
location / {
try_files $uri $uri/ /index.php?$args;
}
完整配置:
server {
listen 80;
server_name www.example.com;
root /var/www/wordpress;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
其他常见规则
去掉 index.php
把 /index.php/xxx 变成 /xxx:
rewrite ^/index.php/(.*)$ /$1 permanent;
伪静态成 .html 结尾
if (!-e $request_filename) {
rewrite ^/(.*)\.html$ /index.php?s=/$1 last;
}
检查配置并重载
nginx -t
nginx -s reload
常见坑
坑1:伪静态不生效
配置了伪静态,但 URL 还是 404。
原因1: 程序后台没开伪静态。
ThinkPHP 需要在后台开启"URL 重写"。WordPress 需要在后台设置固定链接。
原因2: Nginx 没重载。
原因3: 规则写错了,比如少了个 $ 或者 last 没加。
坑2:CSS/JS 加载不出来
配置伪静态后,样式全乱了。
原因: 静态文件也被重写到 index.php 了。
解决: 静态文件直接返回,不走重写:
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d;
}
坑3:后台登录跳转不对
WordPress 后台登录后,跳转不对。
原因: 域名配置不对,或者 WordPress 后台地址设置不对。
解决: 确认 WordPress 后台的"站点地址"和"WordPress 地址"都是正确的域名。
坑4:rewrite 和 try_files 冲突
两种写法不能混用:
# 这两种选一种,别都写
rewrite ^(.*)$ /index.php?s=/$1 last;
try_files $uri $uri/ /index.php?$args;
总结
| 框架 | 重写规则 |
|---|---|
| 通用 PHP 框架 | rewrite ^(.*)$ /index.php?s=$1 last; |
| ThinkPHP5/6 | rewrite ^(.*)$ /index.php?s=/$1 last; |
| WordPress | try_files $uri $uri/ /index.php?$args; |
提醒: 配完伪静态,记得在程序后台也开一下对应的开关,两边都要配。
遇到问题加QQ23979811 协助处理