Permanent Redirection Rules in .htaccess File

Last modified: July 31, 2020
You are here:
Estimated reading time: 1 min

We can set http redirection rules in the apache main configuration file, but some case we do not have permission to edit default configuration file (e.g. shared host, cPanel server). In this case, they provide the .htaccess file which is an Apache web server feature to make configuration changes on a per-directory basis. It allows you to take directives that would normally be put in apache’s main configuration files, and put them in a directory specific configuration file instead. In this tutorial, we will discuss how to set permanent redirection rules in the .htaccess file. There are many types of http redirection rules:

301 Permanent redirect.

302 Temporary redirect.

303 Redirect.

307 redirect

308 redirect.

 

Please read our KB https://www.fastycloud.com/tips/kb/types-redirects-htaccess-redirect-tips-tricks/ for more about http redirection types.

 

The 301 redirect is a permanent redirection and is used to indicate to search engines that the originating URL has permanently moved to new URL. This is the best method for implementing redirect on a website. It acts as the most efficient and search engine friendly method for webpage redirection.

Now we will discuss some common permanent 301 redirection rules.

 

HTTP to HTTPS Redirection.

Most of the domains have valid SSL certificate, but in most case, the website does not redirect to https. The given rule is helping you to redirect the website to https from https. Put given below redirection rule in the .htaccess file to redirect to https from all http requests.

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ Error! Hyperlink reference not valid. [L,R=301]

 

Redirect from old files to new files on the same domain.

Assume you have website examle.com. If you want to redirect from example.com/oldfile.php to example.com/newfile.php put the given below rule in the .htaccess file.

Redirect 301 /oldfile.php /newfile.php

 

Redirect old domain to new domain.

Assume you have a website and two domains example.org and example.com for a website and currently you are using example.com and now you decided you want to use example.org for your website. In this case, put given below rule in the .htaccess file.

RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com [NC,OR]

RewriteCond %{HTTP_HOST} ^www.example.com [NC]

RewriteRule ^(.*)$ http://example.org/$1 [L,R=301,NC]

 

Redirect Non www to www

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.

RewriteRule ^(.*)$ Error! Hyperlink reference not valid. [R=301,L]

 

Redirect all file with specific extension to another extension.

For example, if you want to redirect all .htm file to .php

RewriteEngine On

RewriteCond %{REQUEST_URI} .htm$

RewriteRule ^(.*).htm$ /$1.php [R=301,L]

 

If you need any further help please do reach our support department.

 

Was this article helpful?
Dislike 0
Views: 5