Vue2.5 SPA部署到子文件夹后根路由正常,/login等路由返回404如何解决
问题原因
你当前的前端配置完全符合子目录部署要求,不需要调整。出现非根路由404是Vue Router history模式的固有特性导致的:history模式的路由跳转完全由前端劫持实现,服务器上不存在/login这类路径对应的实体资源,用户直接访问或刷新子路由时,服务器找不到对应资源就会返回404。
解决方案
只需要在你的服务端配置所有子目录下的请求,都重定向到子目录内的index.html入口文件即可,不同服务端的配置方法如下:
Nginx
修改对应站点的Nginx配置文件:
location /subfolder { # 替换为你服务器上subfolder文件夹的实际绝对路径 alias /data/www/your_project/dist; try_files $uri $uri/ /subfolder/index.html; }
修改后执行nginx -s reload重启生效。
Apache
在打包后上传到服务器的subfolder根目录下,新增.htaccess文件,内容如下:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /subfolder/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /subfolder/index.html [L] </IfModule>
需要提前开启Apache的mod_rewrite模块。
Tomcat
在subfolder目录下新建WEB-INF文件夹,新增web.xml文件写入以下内容:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <error-page> <error-code>404</error-code> <location>/subfolder/index.html</location> </error-page> </web-app>
配置完成后重启Tomcat服务即可。
内容的提问来源于stack exchange,提问作者Dylan Dylan
相关产品推荐
相关产品推荐

