30-Jun-2023
.
Admin
Hello Friends,
In this tutorial we will go over the demonstration of how to restrict access to a folder with htaccess. this example will help you deny access to one specific folder in htaccess. you will learn how to deny access to files folders through htaccess. In this article, we will implement a deny access to a site with an htaccess file.
Apache allows access to everything inside the Document Root folder by default. This means all subdirectories and their contents can be listed and accessed. However, you can use .htaccess to enhance the security of your Apache Server
Step 1: Deny Access to .htaccess Itself
Open the .htaccess file and add the following line of code to prevent access to the .htaccess file itself; as follows:
# Deny access to .htaccess
<Files .htaccess>
Order allow,deny
Deny from all
</Files>
Step 2: Disable Directory Indexing
The following line in .htaccess will remove directory indexing and make the server respond with a 403 forbidden message.
# Disable directory browsing
Options -Indexes
To simply hide all the contents of the directory without a forbidden message, use the IndexIgnore directive.
# Hide the contents of directories
IndexIgnore *
To hide some filetypes only, use
# Hide files of type .png, .zip, .jpg, .gif and .doc from listing
IndexIgnore *.png *.zip *.jpg *.gif *.doc
Step 3: Prevent access to certain files
Even if you remove directories and files from the listing, they are still accessible if you type the path.
To remove unauthorized access to certain file extensions, use
# Deny access to files with extensions .ini, .psd, .log, .sh
<FilesMatch "\.(ini|psd|log|sh)$">
Order allow,deny
Deny from all
</FilesMatch>
To prevent access to all filenames starting with dot(.) like .htaccess, .htpasswd, .env and others use
# Deny access to filenames starting with dot(.)
<FilesMatch "^\.">
Order allow,deny
Deny from all
</FilesMatch>
You may also password-protect files and directories and store the passwords in a .htpasswd file
# Password protect files
<FilesMatch "^(execute|index|myfile|anotherfile)*$">
AuthType Basic
AuthName "Mypassword"
AuthUserFile <Full Server Path to .htpasswd file>/.htpasswd
Require valid-user
</FilesMatch>
Replace the <Full Server Path to .htpasswd file> with your actual path.
You may also place a .htaccess file inside each sub-directory with specific overrides. The access rules can be directly defined inside Apache’s main configuration file httpd.conf. But if you don’t have access to the main configuration file (which is normally the case if you're using a shared hosting service), you have to resort to .htaccess-based access rules.
Note: Over-riding https.conf settings using .htaccess is only allowed if the AllowOverride Directive is set inside https.conf which is the default case.
I hope it can help you...
#Ubuntu