Spring Boot 2.7.x HTTP to HTTPS Redirect Configuration Guide
Oct 12, 2025 am 08:24 AMintroduction
In modern web application development, the mandatory use of HTTPS has become an industry standard to ensure data security and user trust. Spring Boot applications usually run through an embedded Tomcat or Jetty server, and configuring HTTP requests to automatically redirect to HTTPS is a common need. Although Spring Security provides configurations such as requiresChannel().anyRequest().requiresSecure() and portMapper() to enforce secure channels, in some cases these configurations may not directly implement the intended browser-level redirection of HTTP to HTTPS. This tutorial will delve into this issue and provide a robust solution based on Tomcat Connector.
Spring Security requiresChannel and portMapper mechanism analysis
Spring Security provides powerful security mechanisms, including the ability to enforce the use of secure channels. By adding requiresChannel().anyRequest().requiresSecure() to the SecurityFilterChain configuration, you can ensure that all requests must be accessed over HTTPS.
The following is a common Spring Security configuration snippet in a Spring Boot application:
package tacos.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import tacos.model.User; import tacos.repository.UserRepository; @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity public class SecurityConfig { @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public UserDetailsService userDetailsService(UserRepository userRepository){ return username -> { User user = userRepository.findByUsername(username); if (user != null) return user; throw new UsernameNotFoundException("User " username "not found"); }; } @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{ return httpSecurity.authorizeRequests() .antMatchers("/design","/orders","/orders/*").hasRole("USER") .antMatchers("/", "/**").permitAll() .antMatchers("/h2-console/**").permitAll() .and() .csrf().ignoringAntMatchers("/h2-console/**") .and() .headers().frameOptions().sameOrigin() .and() .formLogin().loginPage("/login") .loginProcessingUrl("/authenticate") .usernameParameter("user") .passwordParameter("pwd") .defaultSuccessUrl("/design", true) .and() .oauth2Login().loginPage("/login") .and() .logout() .and() .requiresChannel().anyRequest().requiresSecure() // Force all requests to use a secure channel.and() .portMapper().http(8080).mapsTo(8443) // Map HTTP to HTTPS port.and().build(); } }
In the above configuration:
- requiresChannel().anyRequest().requiresSecure() instructs Spring Security that only requests over a secure channel (HTTPS) will be processed. If a non-secure (HTTP) request is received, Spring Security will attempt to redirect it to the appropriate secure URL.
- The role of portMapper().http(8080).mapsTo(8443) is to tell Spring Security that when requests for HTTP port 8080 need to be redirected to HTTPS, port 8443 should be used.
Although requiresChannel triggers a redirect, this redirection is handled by Spring Security in its filter chain. In some deployment environments or configurations, this approach may not provide a seamless, direct HTTP to HTTPS browser redirection experience at the Tomcat server level. More direct server-level redirection is usually done in the Web server's connector configuration.
HTTP to HTTPS redirection based on Tomcat Connector
The most straightforward and recommended way to implement HTTP to HTTPS redirection is to configure the Connector of the embedded Tomcat server. This method completes the redirection at the Tomcat level before the request reaches the Spring Security filter chain, thus providing a more efficient and reliable redirection mechanism.
Here is a code example that implements this functionality:
package tacos.config; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TomcatConfig { /** * Configure the embedded Tomcat server and add an HTTP connector for redirection. * @return configured ServletWebServerFactory */ @Bean public ServletWebServerFactory servletContainer() { // Create a TomcatServletWebServerFactory instance TomcatServletWebServerFactory tomcat = new TomcatWebServerFactory() { @Override protected void postProcessContext(Context context) { //Add security constraints SecurityConstraint for all URL patterns securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); // Require the use of secure transmission SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); // Match all paths securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; // Add an additional HTTP connector for redirecting to HTTPS tomcat.addAdditionalTomcatConnectors(redirectConnector()); return tomcat; } /** * Create an HTTP connector and configure it to redirect requests to the HTTPS port. * @return configured Connector instance*/ private Connector redirectConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); //Set the connector protocol to HTTP connector.setPort(8080); // Listen to HTTP port 8080 connector.setSecure(false); // Mark the connector as non-secure connector.setRedirectPort(8443); // Redirect all HTTP requests to HTTPS port 8443 return connector; } }
Code analysis
-
servletContainer() Bean:
- This method returns a ServletWebServerFactory instance, which Spring Boot will use to create and configure the embedded web server.
- We used TomcatServletWebServerFactory and overridden the postProcessContext() method.
- In postProcessContext(), we create a SecurityConstraint. setUserConstraint("CONFIDENTIAL") forces all matching requests to be transmitted over a secure channel (HTTPS). SecurityCollection is configured with addPattern("/*"), which means that this constraint applies to all paths in the application. When Tomcat receives a non-secure (HTTP) request that matches a CONFIDENTIAL constraint, it attempts to redirect it to the Connector's configured redirectPort.
- tomcat.addAdditionalTomcatConnectors(redirectConnector()) is the key step. It tells Tomcat to create an additional HTTP connector in addition to the default connector (usually the HTTPS connector if SSL is configured).
-
redirectConnector() method:
- This private method creates and configures an org.apache.catalina.connector.Connector instance.
- connector.setScheme("http") and connector.setPort(8080): Clearly indicate that this is an HTTP connector listening on port 8080.
- connector.setSecure(false): Mark it as a non-secure connector.
- connector.setRedirectPort(8443): This is the core of redirection. When Tomcat receives a request through this HTTP connector (port 8080), and the request requires secure transmission (defined by SecurityConstraint), it automatically redirects the request to port 8443.
Things to note
-
SSL/TLS certificate configuration:
- The above redirection scheme requires that your Spring Boot application has been correctly configured for HTTPS. This is usually done by configuring the SSL certificate in application.properties or application.yml:
#application.properties server.port=8443 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=your_password server.ssl.key-store-type=PKCS12 server.ssl.key-alias=your_alias
-
Port conflict:
- Make sure that ports 8080 and 8443 are not occupied by other applications.
- If the default HTTPS port of your Spring Boot application is not 8443, please change the setRedirectPort() value in redirectConnector() to the actual HTTPS port.
-
External proxy/load balancer:
- If your application is deployed behind Nginx, Apache, or other load balancer/reverse proxy, these proxies will typically handle HTTP to HTTPS redirection. In this case, you may not need to configure the above configuration inside the Spring Boot application. The proxy server forwards all HTTP requests to the application's HTTPS port.
-
Spring Boot version compatibility:
- The examples in this tutorial are based on Spring Boot 2.7.x. For other versions, the core concepts remain the same, but the specific class names or configuration methods may differ slightly.
-
pom.xml dependencies:
- Make sure your pom.xml includes the spring-boot-starter-web dependency as it will introduce embedded Tomcat.
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency>
Summarize
In Spring Boot 2.7.x applications, it is a direct and efficient method to implement HTTP to HTTPS redirection by configuring the embedded Tomcat Connector. It handles redirects at the server level, providing lower-level control and more reliable behavior than Spring Security portMapper. Combined with SecurityConstraint, this approach ensures that all non-secure requests are forcibly redirected to the secure channel. Be sure to configure SSL/TLS certificates correctly and consider deploying an external proxy or load balancer in your environment to avoid duplicate or conflicting redirect rules.
The above is the detailed content of Spring Boot 2.7.x HTTP to HTTPS Redirect Configuration Guide. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use the -cp parameter to add the JAR to the classpath, so that the JVM can load its internal classes and resources, such as java-cplibrary.jarcom.example.Main, which supports multiple JARs separated by semicolons or colons, and can also be configured through CLASSPATH environment variables or MANIFEST.MF.

UseFile.createNewFile()tocreateafileonlyifitdoesn’texist,avoidingoverwriting;2.PreferFiles.createFile()fromNIO.2formodern,safefilecreationthatfailsifthefileexists;3.UseFileWriterorPrintWriterwhencreatingandimmediatelywritingcontent,withFileWriterover

JavaSPI is a built-in service discovery mechanism in JDK, and implements interface-oriented dynamic expansion through ServiceLoader. 1. Define the service interface and create a file with the full name of the interface under META-INF/services/, and write the fully qualified name of the implementation class; 2. Use ServiceLoader.load() to load the implementation class, and the JVM will automatically read the configuration and instantiate it; 3. The interface contract should be clarified during design, support priority and conditional loading, and provide default implementation; 4. Application scenarios include multi-payment channel access and plug-in verification; 5. Pay attention to performance, classpath, exception isolation, thread safety and version compatibility; 6. In Java9, provide can be used in combination with module systems.

Use the implements keyword to implement the interface. The class needs to provide specific implementations of all methods in the interface. It supports multiple interfaces and is separated by commas to ensure that the methods are public. The default and static methods after Java 8 do not need to be rewrite.

Javagenericsprovidecompile-timetypesafetyandeliminatecastingbyallowingtypeparametersonclasses,interfaces,andmethods;wildcards(?,?extendsType,?superType)handleunknowntypeswithflexibility.1.UseunboundedwildcardwhentypeisirrelevantandonlyreadingasObject

This article explores in-depth the mechanism of sending multiple HTTP requests on the same TCP Socket, namely, HTTP persistent connection (Keep-Alive). The article clarifies the difference between HTTP/1.x and HTTP/2 protocols, emphasizes the importance of server-side support for persistent connections, and how to correctly handle Connection: close response headers. By analyzing common errors and providing best practices, we aim to help developers build efficient and robust HTTP clients.

This tutorial details how to efficiently process nested ArrayLists containing other ArrayLists in Java and merge all its internal elements into a single array. The article will provide two core solutions through the flatMap operation of the Java 8 Stream API: first flattening into a list and then filling the array, and directly creating a new array to meet the needs of different scenarios.

The answer is to use Thread.currentThread().getStackTrace() to get the call method name, and obtain the someMethod name of the call anotherMethod through index 2. Since index 0 is getStackTrace, 1 is the current method, and 2 is the caller, the example output is "Calledbymethod:someMethod", which can also be implemented by Throwable, but attention should be paid to performance, obfuscation, security and inline impact.
