在 Vue 項目中,可以選擇 hash或者 history.pushState() 實現路由跳轉。如果在路由中使用history模式:
export default new Router({
mode: 'history',
base: __dirname,
scrollBehavior,
routes: [index, blog, project, about, list]
})
那么,當我們 npm run build 完成並部署到服務器后,刷新某個路由下的頁面,會出現 404 或者 502 錯誤。
這是因為刷新頁面時訪問的資源在服務端找不到,因為vue-router設置的路徑不是真實存在的路徑。
解決方法
簡單配置下 nginx ,讓所有路由(url)下的頁面重寫到 index.html即可:
server {
listen 80;
server_name www.fayinme.cn;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_vary off;
gzip_disabled "MSIE [1-6]";
autoindex on;
root /www/blogfront/production/current;
index index.html;
location / {
try_files $uri $uri/ @router;
index index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
注意
配置完成后,如果刷新任意頁面(F5)都跳轉到首頁,你需要查看下 app.vue 是否包含了如下代碼:
created() {
this.$router.push('/')
}
如果有,注釋或刪除即可。