Nginx 无法隐藏域名后缀,但可通过 try_files 指令安全隐藏 URL 中的 .php 或 .html 后缀,或通过 /index.php 回退实现 index.php 隐藏;推荐用 $uri $uri/ $uri.php$is_args$args 顺序查找,避免 rewrite 循环与路由失效。
Nginx 本身不修改浏览器地址栏显示的域名后缀(如 .com),但能有效隐藏 URL 路径中的 .php 或 .html 后缀,让访问链接更简洁、专业,也利于 SEO 和安全防护。关键不是靠 rewrite 硬套,而是用 try_files 主动查找 + 合理回退,避免重写循环和 404。
这是最稳定、无副作用的方式,适合普通 PHP 页面(非框架项目):
try_files $uri $uri/ $uri.php$is_args$args;
}
about)blog/ 目录)about.php)用户始终看到 https://site.com/about,后台静默运行 about.php,无需改代码。
类似逻辑,只需把 .php 换成 .html,并确保 HTML 文件真实存在:
location / {try_files $uri $uri/ $uri.html;
}
这不是“去掉后缀”,而是让所有动态请求走统一入口,彻底不暴露 index.php:
location / {try_files $uri $uri/ /index.php?$query_string;
}
pathinfo 或正确处理 QUERY_STRING,否则路由失效像 rewrite ^(.*)$ $1.php last; 这类写法风险高:
真正干净的 URL 美化,靠的是精准的文件存在性判断,而不是强行改写路径。