vite + vue3 部署 Nginx 刷新页面 404

2023-11-05 11:33:29 浏览数 (1)

vite vue3 打包部署到 nginx 刷新页面 404

在本地运行没问题,部署到服务器上,能正常访问,但是刷新之后页面 404

原 Nginx 配置

代码语言:javascript复制
 server {
        listen      80;
        root /app/tansci/dist;
        index index.html;
        
        location ~* ^/(tansci) {
            proxy_pass http://127.0.0.1:8080;
            proxy_connect_timeout 30s;
            proxy_send_timeout 40s;
            proxy_read_timeout 40s;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /tansci {
            proxy_pass http://127.0.0.1:8080;
            proxy_read_timeout 30;
        }
   }

修改后的 Nginx 配置

代码语言:javascript复制
server {
        listen      80;
        root /app/tansci/dist;
        index index.html;
        try_files $uri $uri/ /index.html;      # 添加
        
        location ~* ^/(tansci) {
            proxy_pass http://127.0.0.1:8080;
            proxy_connect_timeout 30s;
            proxy_send_timeout 40s;
            proxy_read_timeout 40s;
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /tansci {
            proxy_pass http://127.0.0.1:8080;
            proxy_read_timeout 30;
        }
   }

只需要添加 try_files uri uri/ /index.html; 即可。

vite.config.js 配置文件

代码语言:javascript复制
export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src'),
        },
    },
    
    // 全局样式
    css: {
        preprocessorOptions: {
            scss: {
                additionalData: `@use "@/styles/element/index.scss" as *;`,
            },
        }
    },

    // 反向代理
    server: {
        headers: {
            'Access-Control-Allow-Origin': '*',
        },
        disableHostCheck: true,
        port: 3000,
        proxy: {
            '/tansci': {
                target: url,
                changeOrigin: true,
                pathRewrite: {
                    '^/tansci': '/tansci'
                }
            }
        }
    }
})

问题原因

vite 版本导致,项目版本做了一次升级,原有 vite 是 2.6.4,vue 是 3.2.16,后来升级为 2.9.93.2.25

旧版本

代码语言:javascript复制
"dependencies": {
    "@element-plus/icons": "0.0.11",
    "echarts": "^5.3.2",
    "element-plus": "^2.1.8",
    "vue": "^3.2.16",
    "vue-router": "^4.0.12",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.9.3",
    "axios": "^0.24.0",
    "less": "^4.1.2",
    "less-loader": "^10.2.0",
    "vite": "^2.6.4"
  }

升级后的版本

代码语言:javascript复制
"dependencies": {
    "echarts": "^5.3.2",
    "element-plus": "^2.2.2",
    "vue": "^3.2.25",
    "vue-router": "^4.0.15",
    "pinia": "^2.0.13"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.9.3",
    "axios": "^0.24.0",
    "sass": "^1.51.0",
    "vite": "^2.9.9"
  }

0 人点赞