下面我用**「原理 → 实现方式 → 各服务器配置 → 框架示例 → 常见坑」,给你一份真正能落地的 PHP 伪静态完整详解**。
看完你不仅会配,还知道为什么这么配。
一、什么是 PHP 伪静态?
1️⃣ 概念一句话
伪静态 = 看起来是静态 URL,实际上还是 PHP 动态脚本在处理
/article/123.html (伪静态)
article.php?id=123 (真实)
2️⃣ 为什么要用伪静态?
| 好处 | 说明 |
|---|---|
| SEO 友好 | URL 更短、更清晰 |
| 用户体验 | 好看、好记 |
| 安全性 | 隐藏真实参数 |
| 可维护 | URL 可设计 |
二、PHP 伪静态的工作原理(关键)
浏览器访问流程
浏览器请求 → Web 服务器 → Rewrite 规则
→ 映射到 PHP 脚本 → PHP 处理 → 返回结果
📌 伪静态不是 PHP 实现的,而是 Web 服务器完成的
三、实现伪静态的 4 种方式
| 方式 | 推荐 |
|---|---|
| Apache Rewrite | ⭐⭐⭐⭐⭐ |
| Nginx Rewrite | ⭐⭐⭐⭐⭐ |
| PHP PathInfo | ⭐⭐⭐⭐ |
| 框架路由 | ⭐⭐⭐⭐⭐ |
四、Apache 伪静态(.htaccess)
1️⃣ 开启 Rewrite 模块
a2enmod rewrite
2️⃣ .htaccess 示例
<IfModule mod_rewrite.c>
RewriteEngine On
# 如果是真实文件或目录,直接访问
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# /article/123.html → article.php?id=123
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L,QSA]
</IfModule>
3️⃣ PHP 接收参数
$id = $_GET['id'];
五、Nginx 伪静态(生产主流)
1️⃣ 基础 Rewrite
location / {
try_files $uri $uri/ /index.php?$query_string;
}
📌 这是所有 PHP 框架的核心伪静态规则
2️⃣ 自定义规则
location /article/ {
rewrite ^/article/([0-9]+)\.html$ /article.php?id=$1 last;
}
3️⃣ 完整 PHP location 示例
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
六、PHP PathInfo 方式(不推荐但要懂)
URL
/index.php/article/123
PHP 解析
$path = $_SERVER['PATH_INFO']; // /article/123
缺点
❌ 不利 SEO
❌ 可读性差
❌ 框架基本已替代
七、框架伪静态(推荐方案)
1️⃣ ThinkPHP(Nginx)
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
}
}
2️⃣ Laravel
location / {
try_files $uri $uri/ /index.php?$query_string;
}
3️⃣ Hyperf / Swoole
- 不依赖 Web 服务器
- 框架路由本身就是伪静态
八、真实完整示例(Nginx + PHP)
访问
https://site.com/news/2026/01/10/123.html
Rewrite
rewrite ^/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/([0-9]+)\.html$
/news.php?y=$1&m=$2&d=$3&id=$4 last;
PHP
$id = $_GET['id'];
九、常见坑(90% 的人踩过)
❌ Rewrite 规则顺序错误
- 规则 从上到下
- 先精确 → 后模糊
❌ Apache 没开 Rewrite
AllowOverride All
❌ Nginx rewrite 无限循环
rewrite ^/(.*)$ /index.php last; // ❌
❌ 忘记保留 query_string
try_files $uri /index.php?$query_string;
十、SEO 相关建议
✔ URL 唯一
✔ 301 跳转旧地址
✔ 不要频繁改规则
✔ 静态后缀可有可无(.html)
十一、一句话总结
PHP 伪静态不是 PHP 技术,而是 Web 服务器 + 路由设计的艺术