start learning
71

301 redirect

How to configure 301 redirection for my domain ?

A 301 redirect is a type of HTTP status code that tells search engines and web browsers that a page or URL has permanently moved to a new location. When a web server receives a request for a page or URL that has been permanently moved, it sends a 301 redirect response code to the client, along with the new URL to which the page or resource has been moved.

The purpose of a 301 redirect is to ensure that any incoming links, bookmarks, or search engine rankings for the old URL are transferred to the new URL. This helps to preserve the authority and relevance of the old URL, while also redirecting users and search engine bots to the new location.

301 redirects are commonly used when a website changes its domain name, when a page is moved to a new URL, or when a website undergoes a major restructuring. By implementing 301 redirects, website owners can ensure that their users and search engines are directed to the correct page or resource, without losing any link equity or search engine rankings.

.htaccess is a configuration file used by Apache web servers to configure and control various aspects of website functionality, such as URL redirection, security settings, and caching.

Here are some examples of commonly used .htaccess code snippets:
Redirect all traffic to HTTPS :

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Redirect a specific page or directory to a new location:

Redirect 301 /old-page.html http://www.example.com/new-page.html
Redirect 301 /old-directory http://www.example.com/new-directory/

Prevent hotlinking (displaying images on other websites):

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?example.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ - [NC,F,L]

Set the default page (e.g. index.html) for a directory:

DirectoryIndex index.html

Full code :

    RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Redirect 301 /old-page.html http://www.example.com/new-page.html
OR

    <IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
Redirect 301 /old-page.html http://www.example.com/new-page.html
Redirect 301 /old-page.html http://www.example.com/new-page.html
Redirect 301 /old-page.html http://www.example.com/new-page.html
Redirect 301 /old-page.html http://www.example.com/new-page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

It's important to note that incorrect .htaccess code can cause issues with website functionality, so it's recommended to test any changes thoroughly and make backups before making modifications.