Very often you may need to redirect all wildcard subdomains to root domain in Apache. In this article, we will look at how to do this using .htaccess file in Apache server.
How to Redirect All Wildcard Subdomains to Root Domain in Apache
Here are the steps to redirect all wildcard subdomains to root domain in Apache.
1. Enable mod_rewrite
If you have already enabled mod_rewrite in Apache then you can skip this step. Otherwise, run the following commands to enable mod_rewrite, depending on your Linux system.
Ubuntu/Debian
Open terminal and run the following command to enable mod_rewrite
$ sudo a2enmod rewrite
Redhat/CentOS/Fedora
Open Apache configuration file in a text editor.
$ sudo vi /etc/apache2/httpd.conf
Look for the following line.
#LoadModule rewrite_module modules/mod_rewrite.so
Uncomment it by removing # at its beginning. If you don’t find this line, add it afresh.
Also look for the following Directory tag and change AllowOverride from None to All.
. . .
<Directory /var/www/html>
. . .
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
. . .
</Directory>
. . .
2. Redirect Wildcard Subdomains
Open .htaccess file in a text editor.
$ sudo vi /var/www/html/.htaccess
Let us say you want to redirect all subdomains of your website example.com to its root domain. Add the following lines to your .htaccess file.
# Match only subdomains of example.com RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$ [NC] RewriteRule (.*) http://example.com/$1 [L,R=301,QSA]
In the above example, the first two lines enable mod_rewrite and set the URL rewrite base value. Apache matches requests that contain any subdomain of example.com using RewriteCond, and then redirects it to the root domain using RewriteRule.
If the above code does not work for you, you can alternatively try the following code.
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !example.com$ [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
In the above example, Apache will check if the HTTP Host header is example.com. If not, then it will automatically redirect it to example.com.
3. Restart Apache Server
Restart Apache web server to apply changes.
$ sudo service apache2 restart
That’s it. Now open browser and go to any subdomain on your website (example.com). You will be automatically redirected to the root domain.
Also read:
How to Mount ISO Files in Ubuntu
How to Mount Drive from Terminal
How to Disable mod_deflate in Apache
How to Stop/Prevent SSH Brute Force Attacks
How to Disable SSH Root Login in Linux