Search Our Database
How to redirect domain.com to www.domain.com via Command Line (CLI)
Introduction
Redirecting “domain.com” to “www.domain.com” using .htaccesc ensures consistency in how users access your site, improving SEO and preventing duplicate content issues. This guide helps website administrators set up a 301 redirect, ensuring visitors who type in the non-www version of the domain are automatically redirected to the www version, providing a uniform experience across all URLs.
Prerequisite
- SSH access to server
- Access to your website’s root directory
- Ability to edit the .htaccess file
- Basic understanding of Apache web server configurations.
Step-by-step guide
Step 1: Access to your server
- Access your server via SSH. If you are non-having control panel like DirectAdmin or cPanel, you may continue Step 2 once connected.
Else, if you are having control panel, you will need to switch to your control panel user before continuing on Step 2.sudo su <user>
Step 2: Locate and navigate to website root directory
- Locate your website root directory and navigate to the directory by using cd command.
For the server which not having control panel, the path typically will be as below:cd /var/www/html
For the server which having control panel, the path typically will be as below:
cd /home/<username>/<domain>/public_html/
Step 3: Verify if .htaccess existed
- Once you have reached the website root directory, you will need to verify if the .htaccess file existed.
The.htaccess file is a hidden file, you may use command below to show it.ls -la | grep "htaccess"
- If the .htaccess does not exist, you may run the command below to create
touch .htaccess
chmod 644 .htaccess
Step 4: Edit the .htaccess file to redirect the site
- To edit the .htaccess file, we will be using vi command as below.
vi .htaccess
- Once you have entered editor screen, press i to enable the edit mode and adding lines as below.
RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC] RewriteRule (.*) http://www.domain.com/$1 [L,R=301]
or
RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
- Then press ESC and enter :wq to save.
:wp
- The domain.com should be redirected to www.domain.com
Conclusion
By going through this guidance, you will be able to redirect “domain.com” to “www.domain.com” using .htaccess, ensuring consistent traffic routing and improved site management.
For additional assistance or if you encounter any issues, please contact our support team at support@ipserverone.com.