如何在WordPress站点子目录集成跨主机部署的Next.js项目?
实现WordPress子目录指向跨主机的Next.js项目
因为你的WordPress和Next.js分属不同主机,核心思路是通过反向代理或CDN路由转发,将mysite.com/nextjs的请求转发到Vercel上的Next.js项目,以下是两种最简便的实现方案:
方案一:通过WordPress所在VPS的Web服务器做反向代理
如果你用Nginx:
- 先把Next.js部署到Vercel,拿到它的默认域名(比如
your-next-app.vercel.app) - 登录VPS,找到WordPress站点对应的Nginx配置文件(通常在
/etc/nginx/sites-available/下),在server块中添加以下规则:
location /nextjs/ { # 替换成你的Vercel项目域名 proxy_pass https://your-next-app.vercel.app/; proxy_set_header Host your-next-app.vercel.app; 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; # 适配Next.js的路由和WebSocket proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
- 重启Nginx生效:
sudo systemctl restart nginx
- 修改Next.js项目的
next.config.js,添加basePath配置,确保资源路径正确:
module.exports = { basePath: '/nextjs', }
如果你用Apache:
- 先启用必要的模块:
sudo a2enmod proxy proxy_http proxy_http2
- 在WordPress的
.htaccess文件或Apache的vhost配置中添加规则:
<Location "/nextjs/"> # 替换成你的Vercel项目域名 ProxyPass "https://your-next-app.vercel.app/" ProxyPassReverse "https://your-next-app.vercel.app/" RequestHeader set Host "your-next-app.vercel.app" </Location>
- 重启Apache生效:
sudo systemctl restart apache2
- 同样修改Next.js的
next.config.js设置basePath: '/nextjs'
方案二:用CDN路由转发(无需修改VPS配置)
适合不想折腾VPS服务器配置的场景,以Cloudflare为例:
- 将
mysite.com的DNS托管到Cloudflare - 进入Cloudflare控制台,创建一条路由规则:
- 匹配规则:
mysite.com/nextjs/* - 动作选择「改写 URL」->「动态」,目标 URL 填写
https://your-next-app.vercel.app/$1($1用于匹配原路径的剩余部分) - 确保规则优先级高于其他默认规则
- 匹配规则:
- 修改Next.js项目的
next.config.js设置basePath: '/nextjs' - 测试访问
mysite.com/nextjs,如果需要隐藏真实的Vercel域名,可选择「转发 URL」的200状态码改写(而非302跳转)
关键注意事项
- 必须设置Next.js的
basePath,否则项目内的静态资源、路由会指向根路径,导致404 - 如果用反向代理,需确保VPS防火墙允许对外访问Vercel的域名(通常默认允许)
- 测试前清空浏览器缓存,避免旧缓存影响结果
内容的提问来源于stack exchange,提问作者funerr
相关产品推荐
相关产品推荐

