在Nginx中部署多个项目时,例如部署到
html/test
下时,需要配置vite.config.js
的公共基础路径base
字段
你可以将公共基础路径定义在.env.production
中
# .env.production
VITE_BASE_PATH = '/test'
在vite.config.js
中配置base
属性
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) =>{
// 获取环境变量
const env = loadEnv(mode, process.cwd());
return {
base: env.VITE_BASE_PATH,
}
})
若你是vue项目,则需要不同路由模式配置路由
Hash模式
无需配置
const router = createRouter({
history: createWebHashHistory(''),
routes,
});
history模式
需设置base路径
const router = createRouter({
history: createWebHistory(import.meta.env.VITE_BASE_PATH),
routes,
});
Nginx配置
修改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 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
# 路由为 history 模式需要设置该项
try_files $uri $uri/ /index.html;
}
location ^~/test {
alias html/test;
index index.html index.htm;
# 路由为 history 模式需要设置该项
try_files $uri $uri/ /test/index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}