开发者

Redirect tomcat (as Spring tcServer) to different port

I'd like to do something similar to SSL redirection, but slightly different.

I have a load balancer configured to listen on port 80 (HTTP) and 443 (HTTPS).

The load balancer does not have the ability to do any SSL redirection because if it did my life would be too easy (it's Amazon's Elastic Load Balancer, btw).

I have Tomcat (tcServer) listening on two ports: 80 and 81 (both HTTP).

Port 80 on the LB will take you to port 80 on tomcat. Port 443 on the LB will take you to port 81 on tomcat (same web app).

What I would like is to have port 80 on tomcat send you back to 443 on the load balancer.

And all without touching the deplo开发者_JS百科yed webapp.

Any ideas?


One workaround: create a simple web project which does not contain any pages, just a simple error page for 404 errors which redirects every request to the absolute URL of your load balancer (with a https:// link). Then configure Tomcat to use this application on the port 80 (i.e. deploy as ROOT.war) and serve your original application on port 81.


So apparently I over thought this (well, I was kind of led into over thinking it based on some forums I was reading). In any event, here's what worked (and is working - we're in production).

  1. Go get Tuckey's URLRewrite filter and add it first in your web.xml on /*
  2. Add urlrewrite.xml to /WEB-INF/ and put in a default configuration.
  3. Hit /rewrite-status on your application (from localhost) to make sure it's running properly.
  4. Create a rule that will look for Amazon's X-Forwarded-Proto header and makes sure its value is equal to "HTTPS"; if not, have it forward back to https://....

And you are done. The final config looks like:

/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>
</filter-mapping>

/WEB-INF/urlrewrite.xml

<rule match-type="regex">
    <condition type="header" operator="notequal" name="X-Forwarded-Proto">^HTTPS$</condition>
    <from>^.*$</from>
    <to type="permanent-redirect" last="true">https://%{server-name}%{request-uri}</to>
</rule>

You only need tomcat running on one port for this. You have two choices for how to enable URLRewrite.

  1. You can include urlrewrite.xml directly in your WAR and it will just work automagically. You will need to add a rule to disable it for your development environment in that case (you can add an additional condtion on port="80" for enable the rewrite only when listening on port 80, which is production, while development will probably be on 8080).
  2. You can add URLRewrite to the Tomcat lib directory and add the filter to the main web.xml for Tomcat. The advantage is that you don't have to modify your application in order to do it.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜