Directing your users from a naked domain (e.g., example.com ) to a www-prefixed domain (e.g., www.example.com ) is a common practice in web management. It ensures consistency in the URL users interact with, and, when configured correctly, it can have SEO benefits as well.
The Apache HTTP server provides a straightforward way to perform this redirection. The mod_rewrite module, bundled with Apache, enables web administrators to redirect users based on conditions. The most common use-case is to redirect traffic from the naked domain to its www equivalent.
If you have a virtual host file for your domain, you can add a few lines to achieve this redirection. If not, these configurations typically reside in the main Apache configuration file or the .htaccess file in your website's root directory.
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.
$ sudo systemctl restart apache2 # Ubuntu, Debian $ sudo systemctl restart httpd # CentOS and Red Hat
Comment anonymously. Login not required.