Guide to 301 Redirects with an .htaccess File

A 301 redirect is a way to redirect one URL to another URL permanently. It is a crucial tool in website maintenance and SEO because it helps preserve the link equity of the original URL and passes it to the new URL. In this guide, we’ll show you how to implement 301 redirects using an .htaccess file.

Step 1: Create an .htaccess file If you don’t already have an .htaccess file, create one in the root directory of your website using a text editor like Notepad or TextEdit. Save the file as “.htaccess” (without quotes) and make sure it is saved as plain text.

Step 2: Redirect a Single Page To redirect a single page, add the following line of code to your .htaccess file:

bash
Redirect 301 /oldpage.html http://www.example.com/newpage.html

This code tells the server to redirect any requests for “oldpage.html” to “http://www.example.com/newpage.html” with a 301 status code. Make sure to replace “oldpage.html” with the URL of the old page and “http://www.example.com/newpage.html” with the URL of the new page.

Step 3: Redirect an Entire Domain To redirect an entire domain, add the following line of code to your .htaccess file:

arduino
Redirect 301 / http://www.newdomain.com/

This code tells the server to redirect any requests for the old domain to the new domain with a 301 status code. Make sure to replace “http://www.newdomain.com/” with the URL of the new domain.

Step 4: Redirect Non-www to www To redirect non-www URLs to www URLs, add the following lines of code to your .htaccess file:

perl
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

This code tells the server to rewrite any non-www URLs to www URLs with a 301 status code.

Step 5: Save and Upload Your .htaccess File Once you have made your changes, save your .htaccess file and upload it to the root directory of your website using FTP or your web host’s file manager.

Congratulations, you have successfully implemented 301 redirects using an .htaccess file! Remember to always test your redirects to ensure they are working correctly.