Py学习  »  NGINX

Vue项目部署Nginx

取舍🍂 • 4 年前 • 220 次点击  
阅读 36

Vue项目部署Nginx

下载Nginx

以windows版为例,下载niginx压缩包并解压到任意目录,双击nginx.exe,在浏览器中访问http://localhost,如果出现Welcome to nginx!页面则说明成功。

nginx常用命令如下:

nginx -h        # 打开帮助
nginx -t        # 检查配置文件是否正确

# 以下命令均要先启动nginx才能执行
nginx -s stop   # 停止
nginx -s quit   # 退出
nginx -s reopen # 重新启动(注意不会重新读取配置文件)
nginx -s reload # 重新读取配置文件
复制代码

部署项目到Nginx根目录

对于vue-cli创建的项目,修改vue.config.js文件(位于项目根目录下,没有的话自行创建)

module.exports = {
  // 开发环境中使用的端口
  devServer: {
    port: 8001
  },
  // 取消生成map文件(map文件可以准确的输出是哪一行哪一列有错)
  productionSourceMap: false,
  // 开发环境和部署环境的路径
  publicPath: process.env.NODE_ENV === 'production'
    ? '/'
    : '/my/',
  configureWebpack: (config) => {
    // 增加 iview-loader
    config.module.rules[0].use.push({
      loader: 'iview-loader',
      options: {
        prefix: false
      }
    })
    // 在命令行使用 vue inspect > o.js 可以检查修改后的webpack配置文件
  }
}
复制代码

在vue项目根目录中使用命令npm run build创建输出文件,将dist文件夹下的所有内容复制到nginx目录下的webapp/内(没有的话自行创建)。

修改nginx目录中的conf/nginx.conf文件,在 http -> server 节点中,修改location节的内容:

location / {
    root   webapp;
    index  index.html index.htm;
}
复制代码

在nginx根目录使用命令nginx -s reload即可在浏览器中通过http://localhost访问项目。

多个项目部署到Nginx

有时一个Nginx中放了好几个子项目,需要将不同的项目通过不同的路径来访问。

对于项目1而言,修改vue.config.js文件的publicPath

publicPath: '/vue1/'
复制代码

对于项目2而言,修改vue.config.js文件的publicPath

publicPath: '/vue2/'
复制代码

分别在vue项目根目录中使用命令npm run build创建输出文件,将dist文件夹下的所有内容复制到nginx目录下的webapp/vue1和webapp/vue2内(没有的话自行创建)。

修改nginx目录中的conf/nginx.conf文件,在 http -> server 节点中,修改location节的内容:

location /vue1 {
    root   webapp;
    index  index.html index.htm;
}

location /vue2 {
    root   webapp;
    index  index.html index.htm;
}
复制代码

在nginx根目录使用命令nginx -s reload即可在浏览器中通过http://localhost/vue1、http://localhost/vue2访问项目1、项目2。

端口代理

当前后端项目分别部署在同一台机器上时,由于无法使用相同的端口,故后端一般会将端口号设置成不同的值(例如8080),但是当前端向后端请求资源时还要加上端口号,未免显得麻烦,故利用可以nginx将前端的指定路径代理到后端的8080端口上。

conf/nginx.conf文件中增加location

location /api {
    proxy_pass http://localhost:8080/api;
}
复制代码

这样,当前端访问/api路径时,实际上访问的是http://localhost:8080/api路径。

其他

联系

欢迎大家加入我的前端交流群:866068198 ,一起交流学习前端技术。博主目前一直在自学Node中,技术有限,如果可以,会尽力给大家提供一些帮助,或是一些学习方法.

最后

If you have some questions after you see this article, you can contact me or you can find some info by clicking these links.

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49438
 
220 次点击