Blocking Git Repository Access Through The Browser

March 24, 2013

When initialising a git repository, the default behaviour is for the .git directories to be within the working tree. When you use git for web development, these .git files can be browsed to in the web browser. For example,

will allow access to your git config settings. I am going to discuss some options to make sure that these git files cannot be browsed to by the public.

It is possible to set up your repository to store the .git folders outside of your work tree – all these files are then out of the document root and out of Apache’s reach. To do this you need to create the .git folder and then tell git where everything should be when you run the git init command.

$ mkdir ~/
$ cd ~/
$ git --work-tree=/var/www/htdocs/ --git-dir=/home/someuser/ init

I have a site where the git repository is set up this way and it works perfectly fine, up to the point where you forget that it has a slightly unusual setup and it catches you out! Additionally, having to type this long winded command instead of simply just doing git init is very tedious, so I prefer to just let git keep its files within the working tree and solve the Apache issue with, well, Apache.

In the Apache config, you can deny access to any of the .git files with the following:

<LocationMatch ".*/.git/">
Options None
Order Deny,Allow
Deny from all

Now here is the really clever bit. The chances are, you host a few websites on the same server. Some of them will be using git and some of them won’t. Some of them may start using git at a later date. You probably want to apply this LocationMatch to all sites to safeguard them all. If, like me, you use Apache on a Debian based system, What you can do is create this file and put the configuration in it:


The default apache2 config file will include anything within the conf.d directory for all your sites, so once you have restarted Apache, all your sites will be denying access to any .git files.