HTTP 301 Moved Permanently
Overview
The HTTP 301 Moved Permanently
status code indicates that the requested resource has been permanently moved to a new URL provided by the Location
header in the response.
Purpose
The HTTP 301 response is used to redirect clients to a new URL, indicating that the resource they are trying to access has been permanently moved to a new location.
Usage
Client Behavior:
- Send Request: The client sends an HTTP request to a resource’s URL.
- Receive Response: The client receives the HTTP 301 status code along with the new URL in the
Location
header.
Server Behavior:
- Identify Moved Resource: The server recognizes the request for a resource that has been permanently moved.
- Send Response: The server sends a
301 Moved Permanently
response, providing the new URL in theLocation
header.
Scenarios
- URL Changes: When the URL of a resource (like a webpage or API endpoint) changes permanently.
- SEO Practices: To ensure search engines index the new URL and not the old one.
Sequence Diagram
Illustrating the process for an HTTP 301 response:
sequenceDiagram participant Client participant Server as Web Server Note over Client: Client requests an old URL Client->>Server: GET /old-page HTTP/1.1 Note over Server: Server redirects to the new URL Server->>Client: HTTP/1.1 301 Moved Permanently Server->>Client: Location: /new-page
Curl Request and Response Example
Using Curl to request a resource that has been permanently moved:
curl -i http://example.com/old-page
# Expected response: HTTP/1.1 301 Moved Permanently
# Location: http://example.com/new-page
PHP cURL Request and Response Example
PHP script using cURL to handle a request to a URL that has been permanently moved:
<?php
$ch = curl_init('http://example.com/old-page');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 301) {
$newUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
echo "The resource has been moved permanently to: " . $newUrl;
}
curl_close($ch);
?>
Python Request and Response Example
Python script to send a GET request and handle a 301 Moved Permanently response:
import requests
response = requests.get('http://example.com/old-page')
if response.status_code == 301:
print("Resource moved permanently to:", response.headers['Location'])
Apache Configuration for HTTP 301 Moved Permanently
Configuring Apache to redirect a URL permanently:
<VirtualHost *:80>
ServerName example.com
RedirectPermanent /old-page http://example.com/new-page
</VirtualHost>
NGINX Configuration for HTTP 301 Moved Permanently
Setting up NGINX to handle permanent redirection of a resource:
server {
listen 80;
server_name example.com;
location /old-page {
return 301 http://example.com/new-page;
}
}
HTTP 300 Multiple Choices HTTP 302 Found