Apache
If on your VPS is running Apache web server, you’ll also need to edit the .htaccess file. So to do that, make sure that you can connect to your VPS via root with sudo privileges.
By the way, by default, Apache doesn’t allow the use of .htaccess file, so you will need to enable that.
- Connect to your VPS as root with sudo privileges.
- Enable mod_rewrite by running the following command:
sudo a2enmod rewrite
- After that, you need to restart Apache web server on your VPS:
sudo systemctl restart apache2
- Enable .htaccess with the command:
sudo vi /etc/apache2/sites-available/000-default.conf
Then add the following code before the line:
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
After that, restart Apache.
To create the .htaccess file, use this command:
sudo vi /var/www/html/.htaccess
- Then add the following lines to the file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
Replace yourdomain.com with your actual domain name and save it.
- Then restart the Apache server on your VPS:
sudo systemctl restart apache2
Nginx
If you have VPS with NGINX, follow the tutorial below to redirect non-www URLs to www:
- Log in to your VPS using via SSH.
- Navigate to the directory /etc/nginx/.
- Then use this command to view the directory content:
sudo ls - la
- Next enter your NGINX password.
- Type in the following command to edit the nginx.conf file:
sudo nano nginx.conf
- Add the following lines of code, replacing yourdomainname.com with your actual domain name:
server {
server_name yourdomainname.com;
return 301 $scheme://www.yourdomainname.com$request_uri;
}
- Then you need to enter the following command to restart nginx web server on your VPS:
sudo systemctl restart Nginx
In addition to redirecting non-www to www URLs, you can also run other redirects through NGINX, such as HTTP to HTTPS and other page redirects.