nginx部署vue项目

nginx 是一个高性能的 HTTP 和反向代理服务器。因此常用来做静态资源服务器和后端的反向代理服务器。本文主要记录使用 nginx 去部署使用 vue 搭建的前端项目,项目基于 vue 官方的脚手架 vue-cli 构建。

打包 vue 项目

npm run build

通过上面命令后打包好的静态资源将输出到 dist 目录中。如图所示

 

 安装 nginx

到 nginx 官方下载系统相关的 nginx 版本安装

windows 环境

下载相应的 windows 版本解压,解压后如图所示

 

 启动命令:

cd D:\ProgramFiles\nginx-1.12.2\nginx-1.12.2
start nginx

查看 nginx 任务进程 (ps: 需要在安装的根路径下执行)

tasklist /fi "imagename eq nginx.exe"

如图所示

 

 修改 nginx 配置文件,配置文件为 conf 下的 nginx.conf, 修改 nginx.conf 中的 server 配置片段

 server {
        listen       8888;# 默认端口是 80,如果端口没被占用可以不用修改
        server_name  localhost;
    #charset koi8</span>-<span style="color: rgba(0, 0, 0, 1)">r;

    #access_log  logs</span>/<span style="color: rgba(0, 0, 0, 1)">host.access.log  main;
    root        E:</span>/vue/my_project/<span style="color: rgba(0, 0, 0, 1)">dist;#vue项目的打包后的dist

    location </span>/<span style="color: rgba(0, 0, 0, 1)"> {
        try_files $uri $uri</span>/<span style="color: rgba(0, 0, 0, 1)"> @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
        index  index.html index.htm;
    }
    #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
    #因此需要rewrite到index.html中,然后交给路由在处理请求资源
    location @router {
        rewrite </span>^.*$ /<span style="color: rgba(0, 0, 0, 1)">index.html last;
    }
    #.......其他部分省略

}

完成 nginx 配置后重新加载配置文件,命令如下(ps: 需要在安装的根路径下执行):

nginx -s reload

浏览器中访问:http://localhost:8888

通常情况下 ngxin 是安装到单独的服务器上,因此一般是把 vue 打包后的 dist 仍到服务上的具体位置,然后修改 nginx.conf 的 root 路径来指向我们的 dist。

linux 环境

通常情况下很少使用 windows 来作为 nginx 的服务器,一般使用 linux。对于 linux 安装 nginx 有两种方式,一种是使用官方已经编译好的包来安装,一种是使用源码构建安装。

第一种方式参考官方地址https://nginx.org/en/linux_packages.html#stable

第二种方式参考官方地址https://nginx.org/en/docs/install.html中的 Building from Sources 片段,这种实际上就是下一个 tar.gz 包仍到 linux 服务去自己编译。

在 linux 服务上和 window 环境上使用 nginx 部署 vue 项目并没有太大差异,把构建好的 vue 项目 dist 上传到 linux 服务上,通用修改 nginx 服务器中的 root 来指向 dist 就 ok 了,然后使用

# centos 7
systemctl restart nginx.service
# centos 6
service nginx restart

或者是平滑重启

service nginx reload