Disable HTTP Access to .git Without .htaccess

Long story short. If you’re working with Git repositories you’ll notice they have a .git directory and sometimes a .gitignore. Git makes it quite convenient to deploy applications to production servers directly using git clone instead of git archive, but that might leave a possible security issue on your production server — the .git directory might be accessible.

There are several ways to get rid of that. You might use an .htaccess file to prevent access if you’re using the Apache web server. You might use location and deny from all in your configuration files to achieve the same on nginx. Or you might actually use git archive for every update that you do on your production server. But I got an easier solution. Much easier.

If you look closer at where the .git directory is stored in your repository, you’ll notice that it’s only at the top-level, i.e. at the root of the repository. This is different on Subversion for instance, which stores a .svn directory in each and every subdirectory of your project — makes it less trivial to restrict access, but enough baby-talk, let’s get back to Git.

Since Git stores only one .git directory at the top-level of your repository, why not keep your actual application in a sub-directory? There is no .git folder there, hence you don’t need to do any extra manipulations with your web server, and if you decide to later switch from Apache to nginx, you’ll have less trouble. So in your Git repo, create a new directory and call it application for instance, then use the git mv command to move all your files to the new directory, commit and push. Your new structure should look something like this:

$ ls -al
drwxr-xr-x  8 user user 4096 2011-01-20 11:37 .git
drwxr-xr-x 10 user user 4096 2011-01-18 19:36 application # Your app

Then simply point your Apache or nginx (or any other) web server to the application directory at your production server. Restart the web server and pull your new layout from the repo. And that’s it! It is now safe to remove any restriction rules to .git folders since it’s outside the application that you’re serving. You can now store database backups next to that application directory too, just make sure you add *.sql to .gitignore unless you’d like to push such backups to your repo.

Yup! One more point to Git over Subversion ;) Oh and by the way, can you find an easter egg on my website?

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

1 comment