Windows服务器IIS反向代理下NextJS对接NodeJS API异常排查
解决Next.js与Express后端API转发404问题
问题分析
当前配置存在两处核心问题:
- Next.js的rewrites配置中,第一个API转发规则的
destination多了一层/api,导致请求路径重复(变为/api/api/users/...) - IIS的
web.config与Next.js的rewrites同时配置API转发,引发路径逻辑冲突
修正方案
1. 修复Next.js的rewrites配置
先纠正next.config.mjs里的路径错误,移除多余的/api:
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: false, async rewrites() { return [ { source: '/api/users/:path*', destination: 'http://localhost:3001/api/users/:path*', // 删除了重复的/api }, { source: '/api/status/:path*', destination: 'http://localhost:3001/api/status/:path*', }, ]; }, env: { API: "https://myurl.com" } }; export default nextConfig;
2. 选择单一转发方式(二选一)
方式一:仅使用Next.js的rewrites(推荐)
如果依赖Next.js自身的转发逻辑,需要修改web.config,移除API相关的rewrite规则,避免冲突:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="iisnode" path="server.js" verb="*" modules="iisnode" /> </handlers> <rewrite> <rules> <rule name="myapp" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="server.js" /> </rule> </rules> </rewrite> <security> <requestFiltering removeServerHeader="true" /> </security> </system.webServer> </configuration>
此方式下,所有请求先进入Next.js,由Next.js负责将API请求转发到3001端口的Express服务。
方式二:仅使用IIS的URL Rewrite
如果想用IIS直接转发API请求,需要删除Next.js的rewrites配置,确保web.config的API规则正确:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="iisnode" path="server.js" verb="*" modules="iisnode" /> </handlers> <rewrite> <rules> <rule name="API" stopProcessing="true"> <match url="^api/(.*)" /> <action type="Rewrite" url="http://localhost:3001/api/{R:1}" /> </rule> <rule name="myapp" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="server.js" /> </rule> </rules> </rewrite> <security> <requestFiltering removeServerHeader="true" /> </security> </system.webServer> </configuration>
对应的next.config.mjs修改为:
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: false, // 移除rewrites配置 env: { API: "https://myurl.com" } }; export default nextConfig;
3. 验证Express后端路由
确保Express服务的路由路径与转发后的路径匹配,示例:
// Express路由示例 app.get('/api/users/id/:id', (req, res) => { const userId = req.params.id; res.json({ id: userId, name: 'Test User' }); });
测试验证
修改配置后,重启IIS、Next.js及Express服务,验证:
- 直接访问
https://myurl.com/api/users/id/30,应返回后端正常响应 - 前端发起API请求,检查是否返回200状态码及正确数据
内容的提问来源于stack exchange,提问作者OCEANBLUE
相关产品推荐
相关产品推荐

