一、本地项目配置
在开发环境中,Vite 项目的资源路径需要正确配置,否则打包后的静态资源会加载失败。
- 打开 VS Code 进入项目根目录。
- 编辑
vite.config.js文件。 - 在
plugins同级位置添加base配置,确保与后续 Nginx 的路由匹配:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: '/delayed-coking-demo/', // 注意前后斜杠
})
二、构建项目
配置完成后,在终端执行构建命令,生成生产环境代码包。
npm run build
确认根目录下生成了 dist 文件夹,其中包含 index.html 及 assets 等资源。
三、服务器环境准备
以 Windows 服务器为例,安装 Nginx 作为 Web 服务器。
- 下载 Nginx:访问官网下载 Stable version 的 zip 压缩包。
- 解压:将压缩包解压至 C 盘根目录,例如
C:\nginx。你会看到nginx.exe以及conf,html等目录。
四、上传项目代码
将本地构建好的资源上传至服务器。
- 进入服务器的
C:\nginx\html目录。 - 新建文件夹
delayed-coking-demo。 - 将本地
dist文件夹内的所有内容(包括index.html和assets)复制粘贴至此新文件夹中。
五、修改 Nginx 配置
SPA 应用通常使用 History 模式路由,刷新页面容易报 404。需要在 Nginx 中配置 fallback 规则。
编辑 conf/nginx.conf 文件,在 http 块中添加或修改 server 配置:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
# 默认根目录
location / {
root html;
index index.html index.htm;
}
# 项目子路径配置
location /delayed-coking-demo {
root html;
index index.html;
try_files $uri $uri/ /delayed-coking-demo/index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

