A 301 redirect is a permanent redirect of a URL or set-of-URLs to a new destination. This is often a necessity in SEO (search engine optimization) considerations. It is utilized by SEO professionals to manage link and maturity value that a page or domain may have earned over its lifetime.
Here, we will cover several types of 301 redirect that a webmaster or SEO may come across.
Info: This tutorial is specifically for Linux servers that utilize the .htaccess file for this purpose.
The first step is to locate the .htaccess file (usually in the root folder of your website) or create one if there is not any. To create an .htaccess file, open a new text file and name it accordingly. It may be necessary to give it a .txt (or other) extension for your operating system to allow it to be saved (some OS will not allow a file to start with a dot (.) The file will then have to be renamed to .htaccess after being uploaded to the server.
Now that the .htaccess file has been located (or created), here are the several options for doing 301 redirects. Each of the following directives should be used on its own line within the .htaccess file. Once the file is updated, it should be uploaded to the root directory of the server. It can then be tested to make sure that the redirect is working properly.
Note: We are assuming the current domain is example.com.
Redirecting one file to another on the same domain:
Redirecting one file to the same file name on another domain:
This will work on a Linux Server or macOS ServerRewriteEngine on
From non-www to wwwRewriteEngine on
From www to non-wwwRewriteEngine on
The flags at the end of each rule are defined as: