vue-router
默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。
如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
当你使用 history 模式时,URL 就像正常的 url,例如 http://yoursite.com/user/id
,也好看!
不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id
就会返回 404,这就不好看了。
所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html
页面,这个页面就是你 app 依赖的页面。
根目录部署
首先,你的项目要拥有以下特权:
- 默认 web 服务器端口(
80
) - 默认 web 服务器目录
nginx 服务器的默认目录是 /usr/share/nginx/html
,你需要将本地 dist
目录下的静态文件上传至该目录。
如果你在 linux 上使用 apt-get
安装 nginx ,可以在 /etc/nginx/conf
下找到 nginx.conf
配置文件。
参照 vue-router 的后端配置示例:
location / {
try_files $uri $uri/ /index.html;
}
完成后,nginx.conf
文件的 location
配置如下:
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html; // 后端配置
}
子目录部署
假设我们要把项目部署在 nginx 服务器的 /usr/share/nginx/html/your_folder
下,可以在 nginx.conf
文件中增加配置:
location /your_folder/ {
alias /usr/share/nginx/html/your_folder;
index index.html index.htm;
try_files $uri $uri/ /your_folder/index.html; // 需要指定 your_folder
}
注意,这里使用 alias 指定站点目录。
root 指定的是父级目录,并且该目录下要含有和 location 后指定名称的同名目录才行,末尾加不加 “/” 无所谓。
alias 指定的是访问目录,并且末尾必须加 “/”,否则找不到文件。
一般情况下,在 location /
中配置 root,在 location /folder
中配置 alias 是一个好习惯。
代理转发
如果服务器的 80 端口已经被 tomcat 或其它服务占用,可以使用 nginx 的 proxy_pass
进行代理转发。
location / {
root /usr/local/tomcat7/webapps/ROOT;
index index.html index.htm;
proxy_pass http://localhost:8080; // 代理 tomcat 端口
}
启动 nginx 服务,就可以通过 http://localhost
访问到 http://localhost:8080
的内容了。
另外,还有一种情况也会用到 nginx 的代理转发。
使用 vue-cli 进行开发时,为了方便本地调试,通常会配置 proxyTable
代理请求:
proxyTable: {
'/api/': {
target: 'https://github.com', // 服务器地址
changeOrigin:true,
pathRewrite: {
'^/api': ''
}
},
}
使用 axios 请求数据
axios.get('/api/user') // 代理请求 https://github.com/api/user
使用 npm run build
命令打包发布之后,原来的请求变成 https://localhost/api/user
,而不是预测的 https://github.com/api/user
,服务器会返回 404 错误。
这是因为我们本地开发的 proxyTable
是配置在 dev 开发环境,而部署时需要配置服务器环境进行代理转发。
location /api/ {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded $proxy_add_x_forwarded_for;
proxy_pass https://github.com/; // 末尾带 “/” 则为 https://github.com/
}
此时,所有包含 /api/
的请求地址都会被重定向到 https://github.com/
,也就是正式环境的服务器地址。
**代码如诗 **
转帖来源于:使用 nginx 部署 HTML5 History 模式的 Vue 项目