使用Vert.x Web Proxy官方示例代码运行返回404错误问题咨询
问题原因与解决方案
核心原因
默认情况下Vert.x Web Proxy会完整转发请求路径到源站:你访问代理服务的http://localhost:8010/foo,代理会原样发送GET /foo请求到8080端口的源站。如果你的源站没有配置/foo路径,自然返回404。
除此之外,你当前的代码还存在2个常见配置遗漏:
- 路由规则只匹配
/foo精确路径,/foo/xxx这类子路径无法命中规则 - 未配置Host头重写,若源站有虚拟主机校验也会返回404
修复后的完整代码
import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.ProxyHandler; import io.vertx.ext.web.handler.impl.PathRewriteHandler; import io.vertx.httpproxy.HttpProxy; public class WebTest { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); HttpClient client = vertx.createHttpClient(); HttpProxy proxy = HttpProxy.reverseProxy(client); proxy.origin(8080,"localhost"); // 可选配置:重写Host头为源站地址,避免源站虚拟主机校验失败 proxy.addHeader("Host", "localhost:8080"); HttpServer server = vertx.createHttpServer(); Router router = Router.router(vertx); // 1. 路由规则修改为匹配所有/foo开头的路径 // 2. 增加路径重写规则:把/foo前缀去掉,转发到源站的对应路径 // 比如代理的/foo -> 源站/,代理的/foo/bar -> 源站/bar router.route(HttpMethod.GET,"/foo/*") .handler(PathRewriteHandler.create().addRewriteRule("^/foo(/.*)$", "$1")) .handler(ProxyHandler.create(proxy)); server.requestHandler(router); server.listen(8010); } }
额外注意事项
- 如果你不需要去掉
/foo前缀,直接确认源站8080端口存在/foo路径即可,不需要加路径重写规则 - 可以通过命令直接校验源站路径可用性:
curl -v http://localhost:8080/foo - 若需要支持POST等其他请求方法,要么把路由规则中的
HttpMethod.GET去掉匹配所有方法,要么额外添加对应方法的路由规则
内容的提问来源于stack exchange,提问作者Factor Three
相关产品推荐
相关产品推荐

