如何在 2 个反向代理链后面强制主机名

一个 spring boot 应用程序托管在 2 个反向代理(链接)后面。

反向代理 1 --> 反向代理 2 --> spring boot 应用程序

并且主机和转发标头未正确链接。有没有办法强制主机为固定值?像“反向代理 1”的主机名?


小唯快跑啊
浏览 94回答 1
1回答

肥皂起泡泡

我已通过更改传入请求中的服务器名称解决了我的问题。我已经为 tomcat 添加了一个阀门:public class HostForceValve extends ValveBase {private final String proxyName;public HostForceValve(String proxyName) {&nbsp; &nbsp; this.proxyName = proxyName;}@Override public void invoke(Request request, Response response) throws IOException, ServletException {&nbsp; &nbsp; org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();&nbsp; &nbsp; MimeHeaders mimeHeaders = coyoteRequest.getMimeHeaders();&nbsp; &nbsp; mimeHeaders.removeHeader("host");&nbsp; &nbsp; final MessageBytes host = mimeHeaders.addValue("host");&nbsp; &nbsp; host.setString(proxyName);&nbsp; &nbsp; request.setRemoteHost(proxyName);&nbsp; &nbsp; request.getCoyoteRequest().serverName().setString(proxyName);&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Valve next = getNext();&nbsp; &nbsp; &nbsp; &nbsp; if (null == next) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; next.invoke(request, response);&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; request.setRemoteHost(proxyName);&nbsp; &nbsp; }}}并将此值添加到 tomcat 嵌入式服务器:@Componentpublic class MyTomcatCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {@Value("${proxyName:}")private String proxyName;@Overridepublic void customize(TomcatServletWebServerFactory factory) {&nbsp; &nbsp; final Collection<Valve> currents = factory.getEngineValves();&nbsp; &nbsp; final ArrayList<Valve> addValves = new ArrayList<>(currents);&nbsp; &nbsp; if (StringUtils.hasLength(proxyName)) {&nbsp; &nbsp; &nbsp; &nbsp; addValves.add(0, new HostForceValve(proxyName));&nbsp; &nbsp; }&nbsp; &nbsp; factory.setEngineValves(addValves);}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java