How To Deny Direct Access To A Folder Using .Htaccess?

Published September 13, 2024

Problem: Restricting Access to Folders

Controlling access to folders on a web server is a security concern. The .htaccess file can deny direct access to folders, protecting data and maintaining website integrity.

Solution: Using .htaccess to Control Access

Creating a .htaccess File

To limit direct access to files in the 'includes' folder, create a .htaccess file in that folder. Add this directive to the file:

Deny from all

This rule stops direct access to any file in the 'includes' folder. It still allows PHP scripts to include files from this folder when needed.

Tip: Verify .htaccess Functionality

After creating the .htaccess file, test it by trying to access a file in the 'includes' folder directly through a web browser. You should receive a "403 Forbidden" error if the .htaccess rule is working correctly.

Blocking Access to submit.php

To stop direct access to submit.php in the root folder, change the existing .htaccess file in the root directory or make a new one if it's not there. Add these rules:

<Files "submit.php">
    Order Allow,Deny
    Deny from all
</Files>

This setup blocks direct access to submit.php while still letting it process form submissions when called by other scripts.

By using these .htaccess rules, you can control access to sensitive files and folders, making your website more secure. Test these settings to make sure they work as expected and don't affect your site's functions.