Search code examples
.htaccesshttp-redirect

How to make a subfolder unreachable and files undownloadable from root directory using htaccess?


I want to make a subfolder, named backups unreachable and files within it downloadable with the aid of .htaccess placed in the home directory. I don't want to create a secondary .htaccess file in the subfolder.

I did several rewrite and deny commands but no effect.


Solution

  • You can do the following with mod_rewrite at the top of the root .htaccess file to block (ie. 403 Forbidden) any requests to /backups or /backups/<anything>. For example:

    RewriteEngine On
    
    # Block any HTTP requests to "/backups" subdirectory
    RewriteRule ^backups($|/) - [F]
    

    Note that when used in .htaccess, the URL-path that then RewriteRule pattern matches against does not start with a slash.

    Alternatively, use mod_authz_core inside an Apache expression to target just the /backups subdirectory. For example:

    # Block any HTTP requests to "/backups" subdirectory
    <If "%{REQUEST_URI} =~ m#^/backups($|/)#">
        Require all denied
    </If>