How do I prevent apache from serving the .git directory?

Solution 1:

This has the same effect as many of the other answers but is much simpler:

RedirectMatch 404 /\.git

This can go into .htaccess or your server config file. It hides any file or directory whose name begins with .git (e.g. a .git directory or .gitignore file) by returning a 404. So not only are the contents of your Git repo hidden, its very existence is hidden too.

Solution 2:

It's not working because you have 'svn' instead of 'git' in the rule. All you have to do is to replace the 'svn' with 'git'.

<Directorymatch "^/.*/\.git/">
  Order 'deny,allow'
  Deny from all
</Directorymatch>

Solution 3:

If you don't use .htaccess files but instead want to use /etc/apache2/httpd.conf (or whatever your server's master conf file is) to hide both .git directories and .gitignore files, you can use the following. I found the answer above for master conf setting did not hide the gitignore file.

# do not allow .git version control files to be issued
<Directorymatch "^/.*/\.git+/">
  Order deny,allow
  Deny from all
</Directorymatch>
<Files ~ "^\.git">
    Order allow,deny
    Deny from all 
</Files>

Solution 4:

If you're on a shared hosting service and don't have access to apache.conf, you can still do it in your .htaccess file, like this:

RewriteEngine On
RewriteRule "^(.*/)?\.git/" - [F,L]

Solution 5:

### never deliver .git folders, .gitIgnore
RewriteRule ^(.*/)?\.git+ - [R=404,L]

# 2nd line of defense (if no mod_rewrite)
RedirectMatch 404 ^(.*/)?\.git+

This works in .htaccess, no http.conf access required. Include this as the first of rewrite rules. Prepend Rewrite On if needed.

From a security angle, I prefer a bogus 404 over an 403, more informative to the attacker. Comment one of the two out, to ensure, the other works for you, too.

Btw, good changes are, your lithmus test for the two are:

http://localhost/.gitignore
http://localhost/.git/HEAD

Tags:

Git

Apache 2.2