nginx 部署 Vue 项目
网页目录:/usr/share/nginx/
配置文件:/etc/nginx/
Vue 生成项目文件
在 Vue 项目中,查看 package.json
中的 scripts
是否有 build
,如果有的话,执行 npm run build
。没有的话,一般会有 build:prod
,那么就执行 npm run build:prod
即可。比如下面是当时我部署时的文件,那么就执行后者。
# package.json
{
...
"scripts":{
"build:prod": "vue-cli-service build"
}
}
命令完成后会生成 dist 目录,即为我们需要部署的 Web 项目文件。
Nginx 配置部署 Vue
1. 首先将 Vue 项目的 dist 目录放入到 nginx 目录中(不放也可以,但是这样好管理)
cp -r ./dist /usr/share/nginx/test-web
2. Nginx 添加配置文件
# vim /etc/nginx/conf.d/test-web.conf
server {
listen 4000; # 绑定的端口
server_name your_ip_or_hostname; # 你的 IP 或者是指向你 IP 的域名
root /usr/share/nginx/test-web; # 网站对应的根目录
index index.html;
location / {
root /usr/share/nginx/test-web;
try_files $uri $uri/ @router;
# 需要指向下面的 @router,否则 Vue 的路由在 Nginx 中刷新会报 404
index index.html;
}
# 1\. 如果访问 xxx/api/name, 那么相当于访问 http:xxx:yy/name
# 2\. 任何一个 / 都不能丢掉!
location ^~/api/ {
proxy_pass http:xxx:yy/;
}
# 对应上面的 @router
# 主要原因是路由的路径资源并不是一个真实的路径, 所以无法找到具体的文件
# 因此需要 rewrite 到 index.html 中,然后交给路由进行处理
location @router {
rewrite ^.*$ /index.html last;
}
}
3. 重新加载 Nginx 后,访问 http://
4. 部署 https: 链接