Home > Enterprise >  Access denied to root folder and files but allow subfolders and files via .htaccess
Access denied to root folder and files but allow subfolders and files via .htaccess

Time:06-28

How can I deny listing the contents of a parent/root files, but allow access to all sub-folders and their files ? Example

**-Root Folder (Do not access)**
    -index.php (cannot be accessed)
    -demo.php (cannot be accessed)
    -.htaccess (for achieving this)
    **-Subfolder-1 (Grant access all files and folders)**
        -index.php
        -example.php
        -Subfolder-1 -Subfolder
    **-Subfolder-2 (Grant access all files and folders)**
        -index.php
        -example.php
        -Subfolder-2 -Subfolder

CodePudding user response:

Default behaviour is to allow access, so you could just block access to the files in the root using mod_rewrite.

For example:

RewriteEngine On

# Block access (403 Forbidden) to the root folder itself
RewriteRule ^$ - [F]

# 403 Forbidden for any file request in the document root
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^[^/] \.\w{2,5}$ - [F]

The second rule above matches requests for files (that include a file extension) in the root directory only. If this request also maps to an actual file then a "403 Forbidden" response is returned. If the request does not map to a real file then a standard "404 Not Found" response is returned (by default).

If, however, you just want to send a 404 (or 403) for all requests to (what "looks like") files in the root then use the following instead, removing the preceding condition:

# 404 Not Found for any request that looks like a file request in the document root
# - including the root directory itself
RewriteRule ^([^/] \.\w{2,5})?$ - [R=404]

By making the entire pattern optional (ie. by surrounding in ^(.....)?$) it matches the root directory as well.

  • Related