How to have Jetty redirect http to https

jetty

I want to redirect all requests for http to https using Jetty (6.1.24). For some reason (my ignorance) this is eluding me. This is what I have:

<New id="redirect" class="org.mortbay.jetty.handler.rewrite.RedirectPatternRule">
  <Set name="pattern">http://foobar.com/*</Set>
  <Set name="location">https://foobar.com</Set>
</New>

In response I get 200 – ok, and the body is the page over http, ie the redirect doesn't occur.

Best Answer

Speaking for Jetty 9... Here's how you can do it provided that your SSL connector already works:

Step 1: Make sure everything goes through SSL by adding this to your web.xml. If you try to access a resource through HTTP, this will return a 403 !SECURE error

<security-constraint>
  <web-resource-collection>
   <web-resource-name>Everything</web-resource-name>
   <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <user-data-constraint>
   <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>
</security-constraint>

Step 2: Have Jetty redirect to HTTPS when it sees a 403 !SECURE error by adding this to your jetty.xml

<New id="tlsHttpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
   <Arg>
      <New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
         <!-- This says... Redirect to https://host:8443 if server returns "NOT SECURE" error -->
         <Set name="secureScheme">https</Set>
         <Set name="securePort">8443</Set>
      </New>
   </Arg>
   <Call name="addCustomizer">
      <Arg>
         <New class="org.eclipse.jetty.server.SecureRequestCustomizer" />
      </Arg>
   </Call>
</New>

<!-- This is your HTTP connector, you should have another one for HTTPS -->
<New class="org.eclipse.jetty.server.ServerConnector">
   <Arg name="server">
      <Ref refid="MyServer" />
   </Arg>
   <Arg name="factories">
      <Array type="org.eclipse.jetty.server.ConnectionFactory">
         <Item>
            <New class="org.eclipse.jetty.server.HttpConnectionFactory">
               <Arg name="config">
                  <!-- defined above -->
                  <Ref refid="tlsHttpConfig" />
               </Arg>
            </New>
         </Item>
      </Array>
   </Arg>
   <Set name="host">localhost</Set>
   <Set name="port">8080</Set>
</New>