SPA路由History模式 刷新404问题
原因
刷新404,为什么,因为本地路径中没有这个真实资源存在,这些访问资源都是在js里渲染的。我们只需要在服务器配置,如果URL匹配不到任何静态资源,就默认跳转index.html。
解决方法
- 使用
nginx
服务器
配置nginx
这里的配置意思是将所有的文件都指向Index.html文件
server {
listen 8089; // 端口
server_name localhost; // 访问地址,默认是本机
location / {
try_files $uri $uri/ @router; // 需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
// 对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
记住修改配置后一定要重启Nginx服务器,否则无效,Nginx相关命令, 自行百度
nginx 代理知识充电:
proxy_pass 的路径,如果不带uri的话,就是直接原路径代理匹配,带有uri的话,就去掉匹配项再匹配,
实例如下:
(1)
访问 http://www.xxxx.com/testa/aaa
后端的request_uri为: /testa/aaa
location ^~ /testa/ {
proxy_pass http://127.0.0.1:8801;
}
(2)
访问 http://www.xxxxxx.com/testa/bbb
后端的request_uri为: /testa/bbb
location ^~ /testb/ {
proxy_pass http://127.0.0.1:8801/;
}
proxy_pass 的路径,如果不带uri的话,就是直接原路径代理匹配,带有uri的话,就去掉匹配项再匹配
- IIS服务器下
相信大家都知道在IIS下解决Vue单页面应用404的方法是使用URL Rewrite,把所有的请求都转到/index.html中。
1、安装
如果IIS中有Web平台安装程序那么打开,在里面搜索url重写安装、添加就可以了。没有的话,独立下载URL Rewrite工具。安装完成后,重新打开IIS,防止没有"URL重写"选项
2、你的网站根目录中创建一个 web.config.xml 文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Handle History Mode and custom 404/500" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后在给出一个 404 页面。
接下来是Vue路由中的配置:
import NotFoundComponent from '@/views/no-found'
{
path: '*',
component: NotFoundComponent
}
至此,IIS下的配置已完成,随便刷新都不会出现404的错误了