前端vue项目通过nginx部署

39 阅读1分钟

前端项目准备

  1. 前端接口请求访问地址
   const config = {
   // 后端接口请求地址
   apiUrl: 'http://192.168.101.XX/XX',
  };
  window.config = config

在vue项目下的public目录下创建一个config.js文件,用于存放后端接口请求地址;存放在此处的优势是,用于后端IP不确定时,可以手动去修改这个配置文件。

    baseURL=window.config.apiUrl;

在封装request请求时,通过环境变量区分环境,获得对应的IP

  1. 将前端项目打包成静态资源并生成dist文件
   npm run build
  1. nginx配置&说明
    server {
        # 默认端口
        listen       80; 
        server_name  192.168.101.101;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            # root   证书项目;
            # 存放资源的路径
            root   /Users/lichengze/Documents/work/jk/cert/frontend/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
    }

在nginx.conf文件下只需要修改存放资源的路径,端口默认80不需要修改 修改好重启就可以了

   nginx -s reload

备注:try_files uriuri uri/ /index.html 一定要加上,页面刷新可能会报nginx 404找不到,这个时候需要重定向到 index.html