直接加try_files $uri $uri/ /index.html;可解决vue history模式刷新404问题,但必须置于独立location /块内,正确配置root指向dist目录,并确保/api/等接口路由前置以避免被拦截。

直接加 try_files $uri $uri/ /index.html; 就能解决,但必须放在正确的 location / 块里,且不能和 PHP 的 location ~ .php$ 冲突。
phpEnv 下 Nginx 配置文件在哪
phpEnv 是 Windows 下的集成环境,Nginx 配置文件路径通常是:C:phpEnv
ginxconf
ginx.conf 或 C:phpEnv
ginxhostyour-site.conf。优先改 vhost 目录下的站点专属配置(如 localhost.conf),避免动主配置引发全局问题。
确认方法:打开 phpEnv 控制面板 → “Web 服务” → 点击“Nginx 配置”或“站点设置”,里面会显示当前生效的配置文件路径。
必须把 try_files 放在 location / 里,而不是外面
常见错误是把 try_files $uri $uri/ /index.html; 写在 server 块顶层,或者塞进 location ~ .php$ 里——这两处都无效。
正确位置是独立的、通用的 location / 块,且它要覆盖所有前端路由请求:
location / {
root C:/phpEnv/www/my-vue-app/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
注意几点:
-
root必须指向你 Vue 打包后的dist目录,路径用正斜杠/或双反斜杠\,单反斜杠会被 Nginx 当转义符处理 - 如果同时跑 PHP 后端(比如 ThinkPHP),
location /api/这类接口路由要写在location /之前,否则会被try_files拦截后返回index.html - 不要在同一个
server块里写两个location /,Nginx 只认第一个
为什么不能用 rewrite 替代 try_files
phpEnv 默认模板里可能有类似 rewrite ^(.*)$ /index.php?s= last; 的规则,这是为 ThinkPHP 等 PHP 框架设计的,对 Vue 前端完全不适用。
vue-composition-api-best-practices
Vue 3 组合式 API 与
热门下载
相关下载
精品课程
相关推荐
/
热门推荐
/
最新课程
phpenv搭建网站 vscode+xdebug+phpenv调试php代码
共1课时 | 426人学习
使用phpenv集成环境安装极致CMS
共2课时 | 301人学习
phpEnv手册
共0课时 | 0人学习
