gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:37:35 31 4
gpt4 key购买 nike

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

反向代理 1 --> 反向代理 2 --> Spring Boot 应用

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

最佳答案

我通过更改传入请求中的服务器名称解决了我的问题。

我已经向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);
}
}

关于java - 如何在 2 个反向代理链后面强制使用主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56852223/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com