When deploying websites with git, the .git directory often contains sensitive information like source code history, configuration files, and potentially even credentials. Leaving this directory publicly accessible creates serious security vulnerabilities.
Here are three effective methods to prevent Apache from serving .git directories:
Method 1: Using DirectoryMatch in Apache Config
<DirectoryMatch "/\.git/">
Require all denied
</DirectoryMatch>
Method 2: FilesMatch Directive
<FilesMatch "^\.git">
Require all denied
</FilesMatch>
Method 3: Using mod_rewrite
RewriteEngine On
RewriteRule \.git/ - [F,L]
After implementing these changes:
$ sudo apachectl configtest
$ sudo systemctl reload apache2
Then verify by attempting to access http://yoursite/.git/ - you should receive a 403 Forbidden error.
For comprehensive protection:
- Set proper file permissions:
chmod -R 750 .git
- Consider using
git archive
for deployment instead of cloning - Regularly audit your web directories for accidental .git exposure
If the directives don't work:
- Verify the directives are in the correct context (server config, virtual host, or .htaccess)
- Check for conflicting rules in other configuration files
- Ensure mod_authz_core is loaded (required for Require directive)
When deploying websites with git, the .git
directory often gets accidentally exposed through web servers. This contains your entire version history, configuration files, and potentially sensitive data. A properly configured Apache server should prevent access to these directories by default.
There are several effective methods to block access to .git
directories in Apache:
# Method 1: Using DirectoryMatch (most comprehensive)
<DirectoryMatch "/\.git">
Require all denied
</DirectoryMatch>
# Method 2: Using FilesMatch (alternative approach)
<FilesMatch "^\.git">
Require all denied
</FilesMatch>
# Method 3: Using mod_rewrite (for complex setups)
RewriteEngine On
RewriteRule "\.git(/|$)" - [F,L]
For maximum security, implement this at the server configuration level (httpd.conf
or apache2.conf
) rather than in .htaccess
files:
# In your main Apache configuration file
<Directory "/var/www/html">
# Other directives...
# Block access to version control directories
<DirectoryMatch "\.(git|svn|hg)/">
Require all denied
</DirectoryMatch>
</Directory>
After implementing these changes, verify they work properly:
curl -I http://yoursite.com/.git/HEAD
# Should return 403 Forbidden
Consider these complementary security steps:
- Set proper filesystem permissions:
chmod -R 750 .git
- During deployment, consider using
git archive
instead of cloning - Regularly scan your site for accidental exposures