Nuxt 3使用Nginx代理时,JS、CSS、SVG静态资源加载失败
解决Nuxt 3代理部署下资源加载404的问题
核心问题分析
你遇到的问题本质是Nuxt 3默认生成相对资源路径,当通过Nginx代理到不同域名时,客户端会从当前访问域名(exampledomain.com)请求资源,但如果路径配置未同步代理域名,就会触发404错误。你尝试的vite.base方向正确,但需要结合Nuxt的专属配置一起调整才能彻底解决。
具体解决方案
1. 修正vite.base配置
确保生产环境的绝对URL结尾带斜杠,避免路径拼接出错:
// nuxt.config.js export default defineNuxtConfig({ // ... vite: { base: process.env.NODE_ENV === 'production' ? 'https://exampledomain.com/' : '/' }, // ... })
2. 配置Nuxtapp专属路径参数
Nuxt 3的app配置项有专门控制资源路径的参数,配合vite.base使用,能确保所有构建产物、静态资源都使用完整URL:
// nuxt.config.js export default defineNuxtConfig({ // ... app: { baseURL: process.env.NODE_ENV === 'production' ? 'https://exampledomain.com/' : '/', cdnURL: process.env.NODE_ENV === 'production' ? 'https://exampledomain.com/' : undefined }, vite: { base: process.env.NODE_ENV === 'production' ? 'https://exampledomain.com/' : '/' }, // ... })
app.baseURL:控制应用路由和资源的根路径,确保基础路径与代理域名对齐app.cdnURL:专门指定静态资源的代理域名,会强制资源使用该完整URL
3. 处理本地静态资源(如SVG)的引用
如果是本地静态资源(比如/icons/wb2-icons-sprite.svg),不要直接写相对路径,通过运行时变量拼接完整URL:
- 先在
nuxt.config.js配置公共运行时变量:
// nuxt.config.js export default defineNuxtConfig({ // ... runtimeConfig: { public: { appBaseUrl: process.env.NODE_ENV === 'production' ? 'https://exampledomain.com' : '' } }, // ... })
- 在组件中引用时拼接完整路径:
const runtimeConfig = useRuntimeConfig() const svgIconUrl = `${runtimeConfig.public.appBaseUrl}/icons/wb2-icons-sprite.svg#wb2-estate-chevron-down`
4. 检查Nginx代理配置
确保Nginx正确传递请求头,避免Nuxt识别错误的源域名:
server { listen 80; server_name exampledomain.com; location / { proxy_pass http://app.example.com; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
验证步骤
- 重新构建生产环境:
npm run build - 启动生产服务:
node .output/server/index.mjs - 访问代理域名,查看浏览器控制台的资源请求路径,确认所有资源均以
https://exampledomain.com/开头
内容的提问来源于stack exchange,提问作者kapitansen
相关产品推荐
相关产品推荐

