Appearance
访问报404问题
我们项目弄好后要打包到服务器上,一般来说都是直接将dist文件夹丢上去到nginx,然后打开www.xxx.com,这时没问题,但是打开www.xxx.com/list刷新时,就会报404的情况。 这是因为在部署单页应用 (SPA) 时经常遇到这个问题?刷新后 404 是因为 Vue Router 的 history 模式和服务器配置不匹配导致的
hash 模式与 history 模式的区别
hash 模式:URL 中带 #号,如http://example.com/#/list
- 原理:浏览器不会将 #后的内容发送到服务器
- 优点:兼容性好,服务器无需特殊配置
- 缺点:URL 不美观,不利于 SEO
history 模式:URL 像传统网站,如http://example.com/list
- 原理:使用 HTML5 History API 实现路由切换
- 优点:URL 更美观,利于 SEO
- 缺点:需要服务器配合处理路由
解决方法
1.将history模式改成hash模式
2.配置nginx
location / {
try_files $uri $uri/ @rewrites;
index index.html;
}
location @rewrites {
rewrite ^.*$ /index.html last;
}
location / {
try_files $uri $uri/ @rewrites;
index index.html;
}
location @rewrites {
rewrite ^.*$ /index.html last;
}
选择合适的路由模式
- 简单项目或对 SEO 要求不高:使用 hash 模式
- 企业级项目或需要 SEO:使用 history 模式并配置服务器