You can host websites on a URL that starts with or without www. The choice could be personal, though sometimes certain CDN specifically require websites to be hosted on a subdomain (www for example) to work.
Either way, you can first configure your Apache to work both with and without www. You can then automatically redirect your visitor from one to another, based on your preference or requirement.
You can automatically redirect between www and non-www (also known as naked domain) versions of your website and vice versa using a .htaccess file. You can also use the Redirect directive in Apache's configuration file or configure redirection from the dashboard if you're hosting on cPanel.
Methods to redirect domain and URL in Apache:
$ sudo a2enmod rewrite #Ubuntu, Debian and SUSE variants Enabling module rewrite. To activate the new configuration, you need to run: systemctl restart apache2
Options | Debian, Ubuntu | openSUSE and SLES | Fedora Core, CentOS, RHEL | macOS | homebrew | xampp |
---|---|---|---|---|---|---|
a2enmod support | yes | yes | no | no | no | no |
Modules to install | none | |||||
Module name | n/a | rewrite | ||||
Loadmodule directive | n/a | LoadModule rewrite_module <module_locations>/mod_rewrite.so |
$ sudo vi /var/www/html/.htaccess
RewriteEngine On RewriteCond %{HTTP_HOST} ^!simplified.guide$ [NC] RewriteRule ^(.*)$ http://www.simplified.guide/$1 [R=301,L]
301 is equivalent to permanent redirect and you can use 302 instead for temporary redirect.
$ sudo a2enmod rewrite #Ubuntu, Debian and SUSE variants Enabling module rewrite. To activate the new configuration, you need to run: systemctl restart apache2
Options | Debian, Ubuntu | openSUSE and SLES | Fedora Core, CentOS, RHEL | macOS | homebrew | xampp |
---|---|---|---|---|---|---|
a2enmod support | yes | yes | no | no | no | no |
Modules to install | none | |||||
Module name | n/a | rewrite | ||||
Loadmodule directive | n/a | LoadModule rewrite_module <module_locations>/mod_rewrite.so |
$ sudo vi /etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80> ServerName simplified.guide Redirect permanent / http://www.simplified.guide/ </VirtualHost>
permanent is equivalent to 301 redirect and you can use temporary instead for 302 redirect.
Related: How to manage Apache service
Comment anonymously. Login not required.