How to redirect a website using .htaccess
Introduction
Website redirection is a common practice used to forward users from one URL to another. It is widely used during domain changes, website restructuring, or when moving from HTTP to HTTPS. In Apache-based web servers, redirection can be efficiently handled using the .htaccess file. This file allows administrators to control redirects without modifying the main server configuration, making it a simple and powerful solution for managing website traffic flow.
Prerequisites
Before setting up a website redirect using .htaccess, ensure the following:
- You have access to your website’s hosting control panel (cPanel or similar)
- You have access to the root directory of your website (public_html)
- The server is running Apache web server (supports
.htaccess) - Backup of the existing
.htaccessfile (recommended before making changes)
IMPLEMENTATION
Redirect website http://mydomain.com to http://www.mynewdomain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain\.com$
RewriteRule ^(.*)$ http://www.mynewdomain.com [R=301,L]
Redirect website mydomain.com with and without www requests to http://www.mynewdomain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^mydomain\.com$
RewriteRule ^(.*)$ http://www.mynewdomain.com [R=301,L]
Redirect requests from http://mydomain.com to http://mydomain.com/subdirectory i.e. redirecting requests from main domain to a sub-directory.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^mydomain\.com$
RewriteRule ^(.*)$ http://www.mydomain.com/subdirectory/ [R=301,L]
Redirect all http (80) requests of a domain to https (443) i.e. redirecting requests from non-secure port to a secure port.
RewriteEngine On
RewriteCond %{SERVER_PORT} !443
RewriteRule ^(.*)$ https://mydomain.com/$1 [R,L]Â
Conclusion
Using .htaccess for website redirection is a simple and effective method to manage traffic flow, improve SEO, and maintain user experience during domain or URL changes. Properly configured redirects ensure that visitors and search engines are automatically directed to the correct pages without errors or broken links. Always test your redirects after implementation to confirm they are working as expected.
