-
Notifications
You must be signed in to change notification settings - Fork 124
Home
Welcome to the fe wiki!
在package.json里面的scripts里面有build:prefix的脚本,里面有设置VITE-PREFIX设置项,就是前端资源打包完成后的统一url前置项,这里假设说修改成VITE_PREFIX=/nightingale,即:
"build:prefix": "node comb_feats ${npm_config_custom_options} && tsc && cross-env NODE_OPTIONS=--max-old-space-size=6096 VITE_PREFIX=/nightingale vite build --mode advanced"
然后执行npm run build:prefix,就会生成打包结果在pub目录下,在index.html中检查到前端资源已经加上了前缀,这里是一个例子
server {
listen 8765;
server_name _;
# 全局跨域设置(可选)
add_header Access-Control-Allow-Origin *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# 后端接口代理
location /nightingale/api/ {
proxy_pass http://[后端服务地址]/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 前端静态资源
location /nightingale/ {
alias [前端构建输出目录]/; # e.g. /root/n9e/pub/
index index.html;
try_files $uri $uri/ /index.html;
}
# 图片字体文档静态资源
location /image/ {
alias [前端构建输出目录]/image/;
}
location /docs/ {
alias [前端构建输出目录]/docs/;
}
location /font/ {
alias [前端构建输出目录]/font/;
}
# 处理 favicon.ico
location = /favicon.ico {
access_log off;
log_not_found off;
}
}```
本地开发环境:http://localhost:8765/nightingale/ 生产环境:http://[域名或IP]:8765/nightingale/
访问路径必须带上末尾的 /
不带末尾 / 会导致 404 错误
确保 alias 路径正确指向构建后的资源目录
确保服务地址能curl通,例如curl http://[后端服务地址]/api/n9e/site-info?key=site_info,正常返回数据即正确
关于为什么要在nginx中分别处理静态资源,比如image,font等,而不是统一的加前缀,原因如下:
Vite 构建产物的资源 只要是通过 import、require 或 CSS/JS 里相对路径引用的资源,Vite 会自动加上 base(即 /nightingale/)前缀。 比如:import img from './assets/logo.png',最终访问路径会是 /nightingale/assets/logo.png。
但是本项目中资源引用方式均为绝对引用,开发过程中使用 /image/xxx.png、/font/xxx.ttf 这种绝对路径,Vite 不会自动帮加前缀。
所以只有 nginx 配置了 /image/、/font/ 才能访问到静态资源。