When you restructure your website, or move your web pages from one location to another, it is important to redirect old pages to their new location so that both website visitors and search engines know that your website has moved. Else they will have to encounter broken links. One of the common website restructuring problems is to remove folder name from URL. So let us take a look at how to remove folder name from URL in Apache web server.
How to Remove Folder Name from URL in Apache
Here are the steps to remove folder name from URL in Apache web server.
Let’s say you run a website and you want to remove folder name ‘apple’ from http://example.com/apple/products/iphone to http://example.com/products/iphone
Before you proceed, please ensure that you have enabled .htaccess (mod_rewrite) in Apache. If not, then here’s how you can do it:
Place your .htaccess file in the root document folder of your website (/var/www/html)
1. Open .htaccess file in a text editor
Open a terminal session or SSH into your Linux system and run the following command
$ sudo vim /var/www/html/.htaccess
2. Remove Folder name from URL
We will add a url rewrite rule to redirect old URLs to new ones after removing the folder ‘apple’ from them.
Add the following code under DOCUMENT_ROOT directory
Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / RewriteRule ^apple/(.*)$ /$1 [L,NC,R]
You can replace the folder name as per your requirement.
In the above code, Apache matches all URLs starting with apple such /apple/product/mobile/iphone and redirects it to /product/mobile/iphone
We also use a few flags such as NC for case insensitive match, R for external redirection. This is temporary redirection. If you want permanent redirection, use R=301 instead, above.
3. Restart Apache web server
Restart Apache web server to apply changes
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]
That’ it! Now Apache will automatically remove folder names from requested URLs and redirect them to new URLs. This will help website visitors and search engines reach the right destination.