vue-router 的 history 模式是个提升颜值的好东西,没有了 hash 的路由看起来清爽许多。html
开发的时候,若是咱们使用 devServer 来启动服务,因为通常不共用端口,咱们通常不存在非根目录的问题。vue
而刷新后 404 的问题能够借助 historyApiFallback 来解决。webpack
但当咱们项目对外开放时,每每没法在域名根目录下提供服务,这个时候资源的访问路径与开发时的根目录就有了区别。nginx
首先,咱们经过 webpack 来配置一下项目中全部资源的基础路径,让这份代码在开发和生产环境中均可以正确找到资源。web
// config/index.js
module.exports = {
dev: {
...
// 开发环境根目录 - 服务根目录 - 绝对路径
assetsPublicPath: '/'
...
},
build: {
...
// 生产环境根目录 - 服务器访问路径 - 绝对路径
assetsPublicPath: '/test/project1/'
...
}
}
// build/webpack.common.conf.js
const config = require('../config')
module.exports = {
output: {
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
}
}
// build/webpack.dev.conf.js
const common = require('./webpack.common')
module.exports = merge(common, {
devServer: {
historyApiFallback: true
}
}
复制代码
而后在提供服务的服务器配置中作以下配置(以 nginx 为例):vue-router
location /test/project1 {
alias .../project1; // 项目的真实路径
index index.html;
try_files $uri $uri/ /test/project1/index.html;
}
复制代码
try_files 会按顺序检查参数中的资源是否存在,并返回第一个找到的资源,若是都没有找到,它会让 nginx 内部重定向到会后一个参数。服务器
对了,因此它的的做用是解决刷新 404 的问题。ui
这里值得注意的是 try_files 的参数是绝对路径。spa
至此,你开启 history 模式的项目就能够顺利的跑在任何路径了。code
欢迎你们点评指正点个赞~ wink