How to Redirect / Rewrite URLs Using .htaccess File

What is .htaccess?

.htaccess stands for Hypertext Access. The .htaccess file is used to modify the Apache web server configuration without modifying the main configuration file. It is a powerful configuration file which controls the directory it is placed in and all the subdirectories underneath it.

Redirect non-www to www URLs:

Add the following code in your .htaccess file to redirect non-www URL to www. It will also work if an individual file is requested, such as http://example.com/test.html.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.com
    RewriteRule (.*) http://www.example.com/$1 [R=301,L]
</IfModule>

The above code is used to redirect all of the requests for example.com domain to www.example.com.

Redirect www to non-www URLs:

Add the following code in your .htaccess file to redirect www URL to non-www.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
    RewriteRule (.*) http://example.com/$1 [R=301,L]
</IfModule>

The above code is used to redirect all of the requests for www.example.com domain to example.com.

Redirect http URLs to https:

Add the following code in your .htaccess file to redirect all of the requests from http to https.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

Redirect https URLs to http:

Add the following code in your .htaccess file to redirect all of the requests from https to http.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

Redirect non-existing pages to index.php:

If the requested page doesn’t exist, the 404 error page will be opened. But we can redirect the page to index.php page instead of 404 error page.

<IfModule mod_rewrite.c>
    RewriteEngine on 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

Redirecting URLs:

Here the .htaccess code to redirect the page in a local site,

Redirect /ols/file/path.html /new/file/path.html

Here the .htaccess code to redirect the page to the external site,

Redirect /old/file/path.html http://www.example.com/new/file/path.html

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *