.htaccess - Hiding a directory in the URL while preserving other files
Solution 1
You will need something like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule /studio/(.*) /studio/tools/$1 [L]
</IfModule>
The problem is it will not work if the requested file is both in the studio-folder and the tools-folder.
But there no way to prevent this, as the server never knows if an URL is meant to refer to /studio/tools/ or /studio/
Edit: You can remove /tools/ from the visible urls like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule /studio/(.*) /studio/tools/$1 [L]
RewriteRule /studio/tools/(.*) /studio/$1 [L,R=302]
</IfModule>
Solution 2
In this example there is not 404 but it only works to hide only one dir
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+dirname/([^\s]+) [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?!^dirname/)^(.*)$ /dirname/$1 [L,NC]
Anonymous
Updated on June 04, 2022Comments
-
Anonymous almost 2 years
I developed a giant studio of tools and each tool has its own directory in the /tools/ folder. So if you have a tool named example, the URL would be /studio-dir/tools/example/.
I'm trying to hide the /tools/ directory from URLs, while making sure other files outside of the /tools/ directory still work. For example, the /index.php file and /admin/ directory should remain.
I tried this, but it only caused massive 404 errors on everything. I know it's probably waay off, I suck with rewriting URLs. :P
RewriteCond %{REQUEST_URI} !^/tools/ RewriteRule ^/?([^/]+)$ /tools/$1 [L]
If you're still confused, I want:
http://www.example.com/studio/tools/example/index.php
To be able to load as:
http://www.example.com/studio/example/index.php
Whilst still keeping the /tools/ directory, and allowing other files outside of the /tools/ directory to load.
Is this possible?
-
Anonymous almost 11 yearsNice! Works wonders. Would there also be a way to force a redirect to remove /tools/ if it's found in the URL?
-
Lars Ebert almost 11 yearsSee my edit for this. Try it out, though, I am not sure if it will result in an infinit loop or not.
-
Anonymous almost 11 yearsIt doesn't loop indefinitely. It doesn't redirect either, lol. But it's okay, I got it all working with the original rule you posted. :)
-
Lars Ebert almost 9 years@User3515241 Then I urge you to read this guide carefully, it will help you to ask better questions in the future: stackoverflow.com/help/how-to-ask