When nginx deploys the vue project, the page is blank or the page is refreshed with 404 problems

Project scenario:

Package and deploy the vue project to run on nginx


Problem Description

问题一:运行时页面白屏。

问题二:页面可以正常显示,当刷新页面的时候页面报404错误。


Cause Analysis:

Page white screen analysis: We can first check the logs/error.log log file under nginx to confirm that my problem is due to the problem of road configuration when the project is packaged.

Page 404 analysis : When we package and deploy the vue project, the address in the address bar is just the route of vue, not the real file directory address. All routes depend on the index.html of the SPA single-page application, so when we refresh, according to the address in the address bar, if the corresponding file cannot be found, 404 will be generated.


solution:

Page white screen solution:

Configure the vue.config.js file in the root directory of the vue project, the code is as follows:

const { defineConfig } = require('@vue/cli-service')

// 打包配置
module.exports = {
  transpileDependencies: true, // 配置需要被 Babel 转译的依赖项。
  publicPath: process.env.NODE_ENV === 'production' ? '/dist/' : './',
  outputDir: "dist", //输出文件目录
  assetsDir: "static", //静态资源文件名称
  productionSourceMap: false, //去除打包后js的map文件
  lintOnSave: false,
  runtimeCompiler: false,//去掉console

  // 解决跨域
  devServer: {
    host:"127.0.0.1:xxxx",// 以上的ip和端口是我们本机的;下面为需要跨域的
    proxy: { //配置跨域 		
      '/api': {
        target: " ", //这里后台的地址模拟的;应该填写你们真实的后台接口
        ws: true,
        secure: false, // 如果是https接口,需要配置这个参数
        changOrigin: true, //允许跨域
        pathRewrite: {
          '^/api': '' //请求的时候使用这个api就可以
        }
      }
    },
    historyApiFallback: true,
  }
}

Page 404 solution:

Configure the nginx.conf file under the conf directory in nginx, the code is as follows:

location /dist {
	alias html/dist;
	index  index.html index.htm;
	try_files  $uri $uri/ /dist/index.html;
}

location @router {
	rewrite ^.*$ /dist/index.html;
}

Explanation: When we visit an address http://localhost:8056/dist/AssetChanges, first determine the path html/dist through alias, and then configure it through try_files. First, we will find $uri under html/dist, which is login file, because there is no login file at this time, we will go to $uri/, which is the file directory of /login/, if it is still not found, it will be redirected to @router, in the defined @router, we will They all point to index.html under the /dist folder. This successfully solves the problem

Guess you like

Origin blog.csdn.net/qq_52700250/article/details/131340903