nginx部署vue的dist文件

  1. 第一步当然是下载了
http://nginx.org/en/download.html
  1. 下载的不用安装,可以直接点击 nginx.exe 文件打开,也可以通过 cmd 打开 nginx
// cd到nginx所在目录,启动nginx
start nginx 
 
// 修改配置后重新加载生效
nginx -s reload
 
// 重新打开日志文件
nginx -s reopen
 
// 测试nginx配置文件是否正确
nginx -t -c /path/to/nginx.conf
 
// 快速停止nginx
nginx -s stop
 
// 完整有序的停止nginx
nginx -s quit

//结束:
taskkill /f /t /im nginx.exe
  1. 修改配置文件 D:\nginx-1.18.0\conf\nginx.conf

#user  nobody;
worker_processes  1;
events { 
    worker_connections  1024;
}
http { 
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server { 
        listen       8888; #监听端口
        server_name  localhost; #监听的域名
        location / { 
            root   dist; # vue打包的文件普遍是dist 文件,此文件夹与conf文件夹同一级别
            index  index.html index.htm;
            # 需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
            try_files $uri $uri/ @router;
        }
        # 对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
        # 因此需要rewrite到index.html中,然后交给路由在处理请求资源
        location @router { 
            rewrite ^.*$ /index.html last;
        }
         # 将localhost:8888 -> localhost:3000 /api 根据 vue 配置文件进行相应修改
        location ~ ^/api[/\w*]*$ { 
            proxy_pass http://localhost:3000;
        }

    }
}
  1. vue.config.js 的配置
module.exports = { 
  publicPath: process.env.VUE_APP_ENV === 'production'
    ? './'
    : './',
  devServer: { 
    'proxy': { 
      '/api': { 
        'target': 'http://localhost:3000',
        'changeOrigin': true,
        'pathRewrite': { 
          '^/api': ''
        }
      }
    },
    'hot': true,
    'port': 8082,
    'open': true
  },
  productionSourceMap: false
}
  1. 配置之后不知道因为什么原因,在后端的接口里面需要添加 /api
    比如:请求的本来是 /user 要变成 /api/user
  2. 又因为我的接口是用 node 自己写的,不分测试部分和生产部分
    所以我的 vue.config.js 需要修改一下:
module.exports = { 
  publicPath: process.env.VUE_APP_ENV === 'production'
    ? './'
    : './',
  devServer: { 
    'proxy': { 
      '/api': { 
        'target': 'http://localhost:3000',
        'changeOrigin': true,
        'pathRewrite': { 
          '^/api': '/api' // 这里修改了,由 " 改为了 '/api'
        }
      }
    },
    'hot': true,
    'port': 8082,
    'open': true
  },
  productionSourceMap: false
}
    原文作者:weixin_43964779
    原文地址: https://blog.csdn.net/weixin_43964779/article/details/109998289
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞