Spring Boot应用程序托管在2个反向代理(链接)的后面。
反向代理1->反向代理2->春季启动应用
并且主机和转发标头未正确链接。有没有一种方法可以将主机强制为固定值?像“反向代理1”的主机名一样?
最佳答案
我通过更改传入请求中的serverName解决了我的问题。
我在tomcat中添加了一个阀门:
public class HostForceValve extends ValveBase {
private final String proxyName;
public HostForceValve(String proxyName) {
this.proxyName = proxyName;
}
@Override public void invoke(Request request, Response response) throws IOException, ServletException {
org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
MimeHeaders mimeHeaders = coyoteRequest.getMimeHeaders();
mimeHeaders.removeHeader("host");
final MessageBytes host = mimeHeaders.addValue("host");
host.setString(proxyName);
request.setRemoteHost(proxyName);
request.getCoyoteRequest().serverName().setString(proxyName);
try {
Valve next = getNext();
if (null == next) {
return;
}
next.invoke(request, response);
} finally {
request.setRemoteHost(proxyName);
}
}
}
并将此值添加到tomcat嵌入式服务器中:
@Component
public class MyTomcatCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
@Value("${proxyName:}")
private String proxyName;
@Override
public void customize(TomcatServletWebServerFactory factory) {
final Collection<Valve> currents = factory.getEngineValves();
final ArrayList<Valve> addValves = new ArrayList<>(currents);
if (StringUtils.hasLength(proxyName)) {
addValves.add(0, new HostForceValve(proxyName));
}
factory.setEngineValves(addValves);
}
}