如何使用http-proxy-middleware代理多目标主机及同URL模式主机?
Hey there! Let me walk you through how to proxy to multiple target hosts with http-proxy-middleware, since I’ve dealt with this exact problem before. I’ll cover both the proxy table method you asked about, plus a flexible approach for when your target URLs are almost identical.
1. 使用代理表(Proxy Table)
The proxy table is perfect when your API routes are clearly segmented and map directly to different hosts. Each entry in the table uses a path pattern as the key, and the corresponding proxy configuration (including the target) as the value.
Here’s a concrete example:
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { // Proxy table setup app.use( createProxyMiddleware('/api/auth', { target: 'https://auth.yourdomain.com', // 对应认证服务的主机地址 changeOrigin: true, pathRewrite: { '^/api/auth': '' } // 可选:转发前去掉前缀 }) ); app.use( createProxyMiddleware('/api/payment', { target: 'https://payment.yourotherdomain.com', // 对应支付服务的主机地址 changeOrigin: true, pathRewrite: { '^/api/payment': '' } }) ); app.use( createProxyMiddleware('/api/user', { target: 'https://user.yourmaindomain.com', // 对应用户服务的主机地址 changeOrigin: true, pathRewrite: { '^/api/user': '' } }) ); };
Each route (like /api/auth) gets forwarded to its own dedicated target host. The changeOrigin flag is crucial here—it ensures the host header sent to the target matches the target’s URL, avoiding CORS or server-side routing issues.
2. 动态Target处理URL相近的主机
If your target URLs are almost identical (e.g., all under https://website.com but pointing to different sub-services), a dynamic router function is your best bet. This lets you decide the target based on the incoming request’s details (path, headers, etc.).
For example, say you have two services under the same base domain:
https://website.com/user-servicehandles user-related requestshttps://website.com/product-servicehandles product requests
You can route requests dynamically like this:
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( createProxyMiddleware('/api', { target: 'https://website.com', changeOrigin: true, // 自定义router函数,根据请求路径动态调整target router: function(req) { if (req.path.startsWith('/api/user')) { return 'https://website.com/user-service'; } else if (req.path.startsWith('/api/product')) { return 'https://website.com/product-service'; } // 默认target,处理未匹配到的请求 return 'https://website.com/default-service'; }, pathRewrite: { '^/api/(user|product)': '' } // 可选:调整转发后的路径 }) ); };
You can get even more granular—check request headers, query parameters, or HTTP methods to route to different targets. For example, if a request has an X-Service-Name header set to analytics, you could route it to https://website.com/analytics-service.
3. 正则表达式匹配复杂路径
If your routes don’t follow a simple prefix pattern, use regular expressions to match paths. For example:
app.use( createProxyMiddleware(/^\/api\/v1\/.*$/, { target: 'https://legacy-api.yourdomain.com', changeOrigin: true }) ); app.use( createProxyMiddleware(/^\/api\/v2\/.*$/, { target: 'https://new-api.yourdomain.com', changeOrigin: true }) );
This routes all /api/v1/* requests to the legacy API, and /api/v2/* to the new one.
Quick Tips
- Add
logLevel: 'debug'to your proxy config to see exactly where requests are being forwarded—it’s a lifesaver for debugging routing issues. - If you’re using frameworks like React or Vue, make sure your dev server (webpack-dev-server/vite) is configured to use these middleware correctly.
内容的提问来源于stack exchange,提问作者user8839735




