4.3
(13)

Last Updated on November 30, 2021 by Amit

The most common use of an htaccess file is to shorten and rewrite URLs so that they can look clean and preety.
Short URLs are often easy to remember and type in a web browser. So instead of typing a long URL you can just use its clean version to go to the original page.

In this article , I am going to show you how to shorten a directory URL with htaccess.

Assuming our directory structure is as shown in the pic below :
folder structure

As you can see above, we have a subfolder named “folderA” in the root directory. The subfolder has 2 files

  1. index.html
  2. index2.html

To access the files by a web browser , we have to type https://example.com/folderA/index2.html .
This is the actual path location to visit the file but if you are not happy with the URL and want to shorten it, say you want to remove the folder name , you can easily do this with
RewriteRule directive.
After removing the folder name from URL , the URL to the file will look something like :
https://example.com/index2.html.

In the next section below, I will show you how a folder name can be removed from URL using htaccess.

Removing folder name from URLs with htaccess file

It’s not a rocket science to remove the folder name from URLs. You can easily do this with just a few lines of code in an htaccess file.
Here I am taking the exect same URL example I mentioned above.

To remove the folder A you can use the following lines of code in your htaccess file . Remember to place the code at the top of your htaccess in root.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) /folderA/$1 [L]

That’s it.
With those lines set in your htaccess file, you will be able to access your index2.html file in “folderA” by visiting example.com/index.html . It makes it as if you requested the file from root folder.

The rule above doesn’t remove folder name from the URL , it just makes it so that you can use the new version to access the file but the file can also be visited by typing the original location. This leaves you with two different URLs pointing to the same location. If you want to remove the folder name completely , you can use the following rule instead :

RewriteEngine on
RewriteRule ^folderA/(.+)$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) /folderA/$1 [END]

I have also written an htaccess tutorial for people who are new to htaccess and wish to learn , if you are interested, you can find the tutorial On this link
I hope the post was helpful. Thanks for reading it.

How useful was this post?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 13

No votes so far! Be the first to rate this post.