If you move your website or blog from subdirectory to root location of your domain, then you will need to redirect all pages in it to their new location. In this article, we will look at how to redirect subfolder to root in Apache.
Redirect Subfolder to Root in Apache
Here are the steps to redirect subfolder to root in Apache. You will need to enable mod_rewrite in Apache in order to redirect pages as per our requirement.
1. Enable mod_rewrite
Open terminal & run the following command to enable mod_rewrite Apache module on Ubuntu/Debian systems. It is already enabled in CentOS/Redhat systems.
$ sudo a2enmod rewrite
Also read : How to Block User Agent in Apache
2. Enable .htaccess in Apache Server
.htaccess file allows you to update Apache server without accessing its server configuration file. By default, Apache does not allow the use of .htaccess file. So open the default Apache server configuration file
$ sudo vi /etc/apache2/sites-available/000-default.conf
Add the following lines just before </VirtualHost> line.
<Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory>
Restart Apache web server to apply changes.
$ sudo systemctl restart apache2
Also read : How to Enable IPv6 in Apache Web Server
3. Create .htaccess file
Open terminal and create .htaccess file
$ sudo vi /var/www/html/.htaccess
Also read : How to Install WordPress in NGINX in Ubuntu
4. Redirect subfolder to root
Let us say you want to redirect pages from subfolder /blog to the root location, then add the following lines in your .htaccess file. Change the string “blog” below to the name of your subfolder.
RewriteEngine on RewriteBase / RewriteRule ^blog/(.*)$ /$1 [R=301,NC,L]
Above we are using base url as home (/) and rewriting all URLs starting from /blog to the root while retaining its URL stub. For example, /blog/sample-page is redirected to /sample-page. R=301 means it is a permanent redirect.
Also read : How to Change Root Password in Ubuntu
5. Restart Apache Server
Restart Apache web server
$ sudo systemctl restart apache2
That’s it. Now Apache will automatically redirect all requests that are originally sent to /blog subfolder, to the root location of your domain.
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.