Redirect HTTP to HTTPS in Undertow

2019-02-21 01:29发布

问题:

How can one configure HTTP->HTTPS redirection in Undertow? I've looked through Undertow's codebase, there are some classes that seem to be relevant (e.g. RedirectHandler). Also, Undertow documentation (Predicates Attributes and Handlers) seems to target exactly this problem among others. But I'm not sure where to start.

Basically, what I'm looking for is some counterpart to Apache's mod_rewrite configuration:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Thanks!

回答1:

This answer pointed in the right direction. Programmatically, one has to add a SecurityConstraint to Builder and set ConfidentialPortManager:

DeploymentInfo servletBuilder = Servlets.deployment();
servletBuilder.addSecurityConstraint(new SecurityConstraint()
  .addWebResourceCollection(new WebResourceCollection()
    .addUrlPattern("/*"))
  .setTransportGuaranteeType(TransportGuaranteeType.CONFIDENTIAL)
  .setEmptyRoleSemantic(EmptyRoleSemantic.PERMIT))
  .setConfidentialPortManager(new ConfidentialPortManager() {
    @Override
    public int getConfidentialPort(HttpServerExchange exchange) {
      return 443;
    }
  }
);