Nginx 中 URL 后缀伪静态需在 server 块内配置 rewrite,推荐用 location ~ .html$ 限定范围并加 last 标志,正则宜用 ^/([^?#]+)\.html$ 并配合 QSA 保留参数,务必通过 nginx -t 和 rewrite_log 验证。

在 Nginx 中,通过 server 块内直接写 rewrite 规则 实现 URL 后缀伪静态(比如把 /about.html 映射为 /about.php),是最基础也最可控的方式。关键不是“能不能写”,而是“写在哪、怎么写、怎么防误伤”。
rewrite 必须放在 server 块内部,且优先匹配路径
规则只对当前虚拟主机生效,不会影响其他站点:
- 正确位置:在
server { ... }花括号内,通常紧贴location / { ... }上方或内部 - 错误位置:写在
http { ... }顶层 → 所有 server 都会执行,极易冲突 - 示例(隐藏 .php 后缀):
rewrite ^/([a-zA-Z0-9_-]+)\.html$ /$1.php last;
访问/contact.html时,Nginx 内部调用/contact.php,浏览器地址栏不变
用 location + rewrite 组合,避免误处理静态资源
直接在 server 级写 rewrite 容易把 /logo.png 或 /style.css 也卷进去。推荐收敛到特定 location:
- 只对带
.html的请求做处理:
location ~ \.html$ {
rewrite ^/(.+)\.html$ /$1.php last;
} - 加
last表示重写后重新进入 location 匹配流程,确保能被location ~ \.php$正确转发给 PHP-FPM - 若只想映射固定几个页面(如首页、关于页),可用精确匹配:
location = /index.html { rewrite ^ /index.php last; }
location = /about.html { rewrite ^ /about.php last; }
注意后缀规则的边界与变量安全
正则稍不严谨就可能匹配过度或漏掉斜杠:
- 避免写成
^/([a-z]+).html$→ 不匹配大写字母或数字,也不支持路径嵌套(如/news/detail.html) - 更稳妥写法:
^/([^?#]+)\.html$,排除查询参数和锚点,再用$1提取路径主体 - 如果目标脚本需要保留原查询参数(如
/user.html?id=123→/user.php?id=123),记得加[QSA]标志(Nginx 中默认继承$args,但显式写上更清晰) - Windows 下路径一律用正斜杠
/,不要用反斜杠;Nginx 不识别C:\这类写法
验证与调试不能跳过
改完配置别急着 reload,先走两步:
- 运行
nginx -t检查语法是否合法 - 临时开启 rewrite 日志:
rewrite_log on;
error_log logs/rewrite.log notice;
重启后查看日志,每条 rewrite 是否触发、如何替换,一目了然 - 用浏览器开发者工具看 Network 面板:状态码是 200(内部重写成功)还是 404(目标文件不存在)或 301(误加了
redirect或R标志)










