Last Updated on February 12, 2022 by Amit

This article is for mod_rewrite beginners who want to learn how to remove a segment from URLs. If you are new to htaccess and URL rewriting you can follow our Basic htaccess tutorial which is designed especially for beginners.

In this article, we will learn how to convert the following URL




If you are using any CMS like laraval on your php website , then you can also customise your URLs with settings but its easy to do this with an htaccess file.

As you can see the URL above has /public directory which is visible to anyone in browser. If you do not want to show this /public segment in URL and want to make your URL short and clean something like https://example.com/file.php , this can be done with RewriteRule directive in htaccess. The shorter version of the URL looks as if the file.php is in the root folder but in reality the file loads from the /public directory via internal rewriting.

RewriteRule to remove /public folder from URLs

The following rule is simple and it allows you to visit the shorter version of the URL. So instead of typing https://example.com/public/file.php you can just visit https://example.com/file.php
Add this to your htaccess in the root folder :

RewriteEngine On
RewriteCond %{REQUEST_URI} !/public
RewriteRule (.*) /public/$1 [L]

With the code above, you will be able to access your URLs without adding /public segment.
Going to https://example.com/file.php will be same as
https://example.com/public/file.php . However you can notice that now you have two different URLs showing the same page content. This can cause duplicate content issues in search engines. To avoid this , you will need to 301 redirect your old URLs to the new one .
The following is the complete rule to remove public directory from URLs :

RewriteEngine On
#Redirect /public/foobar to /foobar
#The condition bellow is to prevent infinite loop error
RewriteRule ^public/(.*)$ /$1 [L,R=301]
#Now map new URL to the old one
#This is an internal rewriting process
RewriteCond %{REQUEST_URI} !/public [NC]
RewriteRule ^(.*)$ /public/$1 [L]

Just remember to put this code at the top of your main root/.htaccess file.
This will redirect all URLs including your homepage to make it look like https://example.com/foobar in a web browser and the contents will load from /public/foobar .

I hope this article was helpful and you enjoyed reading it. If you need more help regarding removing folder name from URLs, just leave a comment below. I will reply you within 30 minutes.

How useful was this post?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 10

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