.htaccess
FilesAccess control is crucial for securing web directories and files. Apache's .htaccess
files provide a flexible way to implement access restrictions, ensuring only authorized users can access certain parts of your website.
To limit access to specific IP addresses, use the following directives in your .htaccess
file:
<Files "admin">
Order Deny,Allow
Deny from all
Allow from 192.168.1.100
Allow from 10.0.0.0/24
</Files>
This example denies access to the "admin" directory to everyone except the specified IP addresses.
Basic authentication can be set up to protect sensitive directories:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
Use the htpasswd
tool to create the .htpasswd
file and add users.
To block unwanted bots or specific user agents:
SetEnvIfNoCase User-Agent "BadBot" bad_bot
Order Allow,Deny
Allow from all
Deny from env=bad_bot
To block requests that do not originate from your site:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https://yourdomain.com/ [NC]
RewriteRule .* - [F]
To restrict access to specific file types:
<FilesMatch "\.(txt|md)$">
Order Deny,Allow
Deny from all
</FilesMatch>
Using .htaccess
for access control enhances the security of your web applications by restricting access based on IP addresses, implementing password protection, blocking malicious bots, and controlling access to specific files and directories. Regularly review and update your .htaccess
configurations to adapt to new security challenges and requirements.