apache下vue history模式404需配置重定向至index.html,核心是让web服务器而非thinkphp接管前端路由,规则须置于.htaccess开头且rewritebase匹配部署路径。

Apache下Vue history模式404重定向到index.html的配置坑
ThinkPHP本身不接管前端路由,Vue的history模式导致刷新页面时,请求直接打到Web服务器(如Apache),而服务器找不到对应路径就返回404。关键不是ThinkPHP改什么,而是让Apache把所有非静态资源、非API请求都fallback到index.html,再由Vue Router接管。
常见错误是只在ThinkPHP的.htaccess里加规则,却没意识到:Vue打包后是纯静态文件,应由Apache优先处理;ThinkPHP的入口index.php根本不会被这次请求触发。
- 确保Vue项目构建输出目录(如
public/或dist/)和ThinkPHP的public/合并部署(即index.html和index.php同级) - 在Apache虚拟主机或
.htaccess中添加以下规则(放在ThinkPHP原有重写规则之前):
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
注意:RewriteBase /要匹配实际部署路径;如果Vue部署在子目录(如/admin/),需改为RewriteBase /admin/并调整index.html路径。
Nginx中Vue history fallback与ThinkPHP共存的rewrite顺序
Nginx没有.htaccess机制,所有逻辑必须写在server块里。最容易踩的坑是把Vue的fallback规则写在ThinkPHP的try_files之后——那样请求早被index.php捕获,根本轮不到Vue。
正确做法:先排除静态资源(js/css/img等),再对非文件、非目录的请求,统一fallback到/index.html;仅当请求明确以/api/、/index.php开头,才交由ThinkPHP处理。
- ThinkPHP默认要求
try_files $uri $uri/ /index.php?$query_string;,但这会拦截所有不存在路径,包括Vue路由 - 替换为更精细的判断:先匹配静态文件,再匹配Vue路由兜底,最后才是PHP入口
location / {
try_files $uri $uri/ @vue;
}
location @vue {
rewrite ^(.*)$ /index.html last;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass php-fpm;
}
其中@vue是命名location,确保所有非静态、非PHP请求都落到index.html;而location ~ \.php$仍保障ThinkPHP接口正常响应。
vue-composition-api-best-practices
Vue 3 组合式 API 与
热门下载
相关下载
精品课程
相关推荐
/
热门推荐
/
最新课程
最新文章
