Home > Enterprise >  Hide directory where css, js, image folder are placed
Hide directory where css, js, image folder are placed

Time:10-01

I want to secure and hide my asset folder from publicity. I hear that can be done with the .htaccess file and change the name from my directory-name to random name of the directory and in that case, users can't know the real name of my directory placed into my public_html. Can someone help me with examples of all kinds of documentation? I didn't try anything because I have really bad knowledge of .htaccess coding. Any help will be thankful.

CodePudding user response:

Well, you can do this, but I'm curious as to the purpose if it's just to casually "hide" the underlying file directory? This doesn't really offer any additional "security" and can also cause issues if you have a front-end proxy that is intended to serve static content. It can also be problematic if you are using a CMS like WordPress as you may need to modify the default behaviour. (Although there may be other developmental issues for which you would choose to do this.)

Ideally, you would do something like this with the Alias directive in the main server config (or vHost container).

In .htaccess you can internally rewrite the request using mod_rewrite. Lets's say you are referencing /assets in the URL, but the actual filesystem directory that this should map to is /secret then you could do the following to simply forward all requests to /secret:

RewriteEngine on

RewriteRule ^assets/(. ) secret/$1 [L]

Only requests for /assets/<something> will be forwarded. A request for /assets or /assets/ will simply result in a 404 (assuming this directory does not actually exist).

To be more selective and only forward requests for specific file types, based on the file extension, then you could do something like the following:

RewriteRule ^assets/(. \.(?:jpg|webp|gif|css|js))$ secret/$1 [L]

You could also check to see whether the target file actually exists before rewriting, but this is generally unnecessary and best avoided since filesystem checks are relatively expensive.

  • Related