NextJS静态导出下window.open()生产环境打开新标签页404问题
解决方案
1. Apache URL重写(最优方案)
在项目根目录(或build目录下)创建.htaccess文件,添加以下规则,让Apache自动将无.html后缀的请求映射到对应的静态文件:
RewriteEngine On # 跳过已存在的文件和目录,避免干扰静态资源加载 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 将非.html结尾的路径重写为带.html的版本 RewriteRule ^([^.]+)$ $1.html [L]
这个规则完全不影响开发环境(开发用NextJS自带服务器),生产环境下/report会自动匹配到build/report.html,完美解决404问题。
2. NextJS导出配置调整
若不想依赖Apache配置,可修改next.config.js,通过trailingSlash和目录结构实现无后缀访问:
/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', trailingSlash: true, }; module.exports = nextConfig;
开启trailingSlash: true后,NextJS会为每个页面生成对应目录(如report/),目录内包含index.html。此时需确保Apache启用了DirectoryIndex index.html(默认开启),访问/report会自动加载report/index.html。
如果你之前试trailingSlash无效,大概率是Apache未正确处理目录索引,可在.htaccess中补充:
DirectoryIndex index.html
3. 组件内路径适配(无环境变量)
如果以上两种方案都不适用,可在组件内通过当前域名判断环境,动态调整路径:
const handleOpenReport = async () => { // 执行异步请求并写入localStorage的逻辑 const isProd = window.location.hostname !== 'localhost'; const targetUrl = isProd ? '/report.html' : '/report'; window.open(targetUrl, '_blank'); };
这种方式无需额外配置,也不用环境变量,只是代码层面做了适配。
关键注意点
- 确保Apache已启用
mod_rewrite模块,Linux环境可通过a2enmod rewrite开启,然后重启Apache。 - 若你的DocumentRoot指向项目根目录而非
build目录,需调整.htaccess中的重写规则,指定build路径:
RewriteRule ^([^.]+)$ build/$1.html [L]
内容的提问来源于stack exchange,提问作者MKF
相关产品推荐
相关产品推荐

