Search Our Database

How to Create Site Redirect Using “.htaccess”

Last updated on |
by

Introduction

One of the most effective ways to perform a page or website redirection is by using the .htaccess file. This file can be found in the public_html directory of your website. If the .htaccess file does not already exist, you can create it manually within the public_html folder.

Important Note: Ensure that the ownership of the .htaccess file is set to the correct username to avoid permission issues.

 

Steps to Redirect Using .htaccess

Step 1: Access the server or control panel

  • You can either access the server via SSH or use the control panel’s File Manager to manage the .htaccess file.

 

Step 2: Open the .htaccess file

  • Locate and open the .htaccess file in the public_html directory.
  • Example DirectAdmin path:
    /home/<user>/domains/<domain-name>/public_html/.htaccess

     

Common Redirect Scenarios Using .htaccess

1. Redirect non-www to www

This rule redirects visitors from domain.com to www.domain.com.

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

 

2. Redirect www to non-www

This rule redirects visitors from www.domain.com to domain.com.

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

 

3. Redirect to a new URL

This rule redirects visitors from old-website.com.my to new-website.com.my.

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^old-website.com.my$ [NC] 
RewriteRule ^(.*)$ http://www.new-website.com.my/$1 [L,R=301,NC]

 

4. Redirect to a new local directory

This rule redirects visitors to a specific subdirectory of the same domain.

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^example\.com [NC] 
RewriteCond %{REQUEST_URI} ^/$ 
RewriteRule ^(.*)$ /subdirectory-name/$1 [L]

 

5. Redirect HTTP to HTTPS

This rule forces HTTP requests to redirect to HTTPS.

RewriteEngine On 
RewriteCond %{SERVER_PORT} ^80$ 
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

 

 

Conclusion

By using the .htaccess file, you can easily manage various types of redirects, such as redirecting from non-www to www, moving visitors to a new URL, or enforcing HTTPS. Each scenario above includes specific rules that can be copied and customized based on your website’s needs.

If you encounter any issues or need further assistance, please contact our support team at support@ipserverone.com.