我有一个独立的 tomcat 服务器(前面没有 apache/nginx),我需要配置它以将特定应用程序的所有传入请求及其 header 重新路由到不同的主机。换句话说,我需要 URL
https://host.company.com/app/<anything here after>
重定向到
https://newhost.company.com/app/<anything here after>
这样
https://host.company.com/app/v1/explore?id=foo&pw=bar&more=crap
被重定向到
https://newhost.company.com/app/v1/explore?id=foo&pw=bar&more=crap
同时不干扰 https://host.company.com/app2
或 https://host.company.com/app3
.
目前,我有 urlrewrite安装在 webapps/app
像这样:
webapps/app/WEB-INF/urlrewrite.xml:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN" "https://www.tuckey.org/res/dtds/urlrewrite4.0.dtd"> <urlrewrite> <rule> <name>Requests to /app/ will be redirected to https://newhost.company.com/app/</name> <from>^/(.*)$</from> <to type="permanent-redirect" last="true">https://newhost.company.com/app/$1</to> </rule> </urlrewrite>
webapps/app/WEB-INF/web.xml:
<filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
重定向到https://newhost.company.com
正在工作,但是没有转发 header ,这是使这项工作成功的关键因素。所以虽然这工作正常:
curl --compressed -H 'Accept-Encoding:gzip' --get 'https://newhost.company.com/app/v1/explore' --data-urlencode 'id=foo' --data-urlencode 'pw=bar' --data-urlencode 'more=crap'
这不是
curl --compressed -H 'Accept-Encoding:gzip' --get 'https://host.company.com/app/v1/explore' --data-urlencode 'id=foo' --data-urlencode 'pw=bar' --data-urlencode 'more=crap'
并使用 -vv
运行上面的代码揭示了问题(为清楚起见被精简):
* Connected to host.company.com (w.x.y.z) port 443 (#0)
> GET /app/v1/explore?id=foo&pw=bar&more=crap HTTP/1.1
< HTTP/1.1 301 Moved Permanently
< Location: https://newhost.company.com/app/v1/explore
* Connected to newhost.company.com (w.x.y.z) port 443 (#1)
> GET /app/v1/explore HTTP/1.1
如您所见,newhost.company.com 的 GET 不包含任何以“?”开头的 uri 数据。使用标准浏览器时,生成的 URL 为 https://newhost.company.com/app/v1/explore
鉴于上述情况,这是有道理的。但是,我需要将 uri 数据传递到 newhost.company.com,但我不知道如何让 tomcat 执行此操作。
注意:出于“安全”目的,将 apache/nginx/etc 放在 tomcat 前面不是一个选项(不是我的要求,来自管理层的命令)
最佳答案
使用 urlrewrite 时您需要将 use-query-string="true"添加到 urlrewrite.xml urlrewrite 标记中,以便它在转发的 URL 上传递查询字符串参数。
更改自:
<urlrewrite>
更改为:
<urlrewrite use-query-string="true">
关于tomcat - 使用tomcat将请求和 header 转发到不同的主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25768345/