How to have Jetty redirect http to https

Solution 1:

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>

Solution 2:

I think that the pattern is matching only the URI. You should use something like:

<New id="forwardedHttps" class="org.eclipse.jetty.rewrite.handler.ForwardedSchemeHeaderRule">
           <Set name="header">X-Forwarded-Scheme</Set>
           <Set name="headerValue">https</Set>
           <Set name="scheme">https</Set>
</New>

See: http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/rewrite/handler/RewriteHandler.html

Solution 3:

I just added the doc: http://wiki.eclipse.org/Jetty/Howto/Configure_SSL#Redirecting_http_requests_to_https