By default, Apache doesn’t allow the use of .htaccess file, so the steps will be a little different:
- Enable mod_rewrite by running the following command:
$ sudo a2enmod rewrite
Then, restart the Apache web server:
$ sudo systemctl restart apache2 - Enable .htaccess with the command:
$ sudo vi /etc/apache2/sites-available/000-default.conf
Add the following code before the <VirtualHost> line:
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
Then, restart Apache. - To create the .htaccess file, enter the command:
$ sudo vi /var/www/html/.htaccess - Add the following lines to the file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301] - Restart the Apache server.
All site visitors using the non-www URL should now be redirected to the www version.
Source: https://www.hostinger.com/tutorials/cpanel/how-to-redirect-non-www-urls-to-www#Apache