Wednesday, 5 June 2024

Implementing HTTP 301 URL Redirects in Spring Boot

 

301: Moved Permanently

The 301 status code indicates that the requested resource has been permanently moved to a new URI, and future references should use the provided new URI.

 

Clients which can update links should automatically update references to the old URI with the new ones returned by the server. The detailed steps look like below.

 

Step 1: Client Makes a Request

The client (e.g., a web browser) makes a request to access a resource at a specific URL.

 

Step 2: Server Responds with 301 Status Code

The server receives the request and responds with a 301 Moved Permanently status code. The response includes a Location header that specifies the new URI where the resource has been moved.

 

Step 3: Client Receives the Response

The client processes the server’s response and recognizes the 301 status code, indicating a permanent move.

 

Step 4:  Automatic Redirection

The client automatically follows the Location header and sends a new request to the specified new URI. This ensures the client retrieves the intended resource from its new location.

 

Step 5: Updating References

If the client has link editing capabilities (such as a browser with bookmarks or a web application with stored links), it should update its stored references.

a.   Bookmarks: The client should update any bookmarks that reference the old URI to point to the new URI.

b.   History: The client should update its browsing history to replace the old URI with the new URI.

c.    Internal Links: In the context of a web application, any internal links or references within the application should be updated to reflect the new URI.

 

Step 6: Future Requests

As client caches this old to new URL mapping in its internal cache, for subsequent requests to the old URI, the client will not send to the server for redirection URL, instead the request is automatically redirected to the new URL directly.

 


Sample response looks like below.

HTTP/1.1 301 Moved Permanently
Location: https://www.myanalytics.com
Content-Type: text/html; charset=UTF-8

To prevent unintended actions, automatic redirection of non GET/HEAD requests will be confirmed by the user. For example,

 

1.   A user submits a form (POST request) to http://mybank.com/trasfer-money.

2.   The server responds with a 301 status, redirecting to https://fakebank.com/transfer-money.

3.   If the browser automatically resends the POST request to the new URL without user confirmation, it might lead to unintended data submission or actions.

 

Follow below step-by-step procedure to build a working application.

 

Step 1: Create new maven project “permanent-redirect”.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>permanent-redirect</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.2</version>
	</parent>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
			<version>2.0.4</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Step 3: Define RedirectController class.

 

RedirectController.java

package com.sample.app.controller;

import java.net.URI;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class RedirectController {

    @GetMapping("/redirect")
    public ResponseEntity<Void> redirect() {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create("https://self-learning-java-tutorial.blogspot.com/"));
        return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
    }
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

Build the Project

Go to the location where pom.xml is located, and execute the command ‘mvn package’. Upon successful completion of the command, you can see a jar file ‘permanent-redirect-0.0.1-SNAPSHOT.jar’ located in target folder.

 

Run the Application

Execute below command to run the application.

java -jar ./target/permanent-redirect-0.0.1-SNAPSHOT.jar

Open the url "http://localhost:8080/api/redirect" in browser, you can see this is redirected to the url "https://self-learning-java-tutorial.blogspot.com". Response header looks like below.


 

Note

A 302 status code indicates a temporary redirect, so browsers do not cache the new URL. Instead, they always send requests to the server, which reads the new URL from the Location response header and redirects to it. For permanent moves, always use a 301 status code. In this case, browsers cache the response, reducing the load on the server.

You can download the application from this link


Previous                                                    Next                                                    Home

No comments:

Post a Comment