1. Deny Access to .htaccess Itself
Add the following lines in your .htaccess file to prevent access to .htaccess file itself.
# Deny access to .htaccess
<Files .htaccess>
Order allow,deny
Deny from all
</Files>
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 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
3. Prevent access to certain files
Even if you remove directories and files from listing, they are still accessible if you type the path.
To remove unauthorized access to cetain 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>