This is important if you are automatically deploying web-apps using git (for example with a GitHub deploy key).

What’s this about?

If you are deploying your web-apps using git pull, either manually or automatically, chances are you are deploying straight to the web-root, which would then include a hidden “.git” directory. By default, your web server would serve that directory and all its contents.

What’s inside the “.git” directory?

Inside the .git directory, is all the git related data. This includes metadata and diffs. Among the metadata is every commit name and email address. And of course, serving the .git directory basically means anyone has access to your source code.

How to stop serving the “.git” directory? (Apache Web Server)

This can be accomplished easily with a few lines added to the config file.
Look for <Directory *> entries in the configuration file, and underneath them, add the following lines:

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

Now simply reload the server configuration (on Debian/Ubuntu) with systemctl reload apache2 and on some other distributions it might be systemctl reload httpd

Apache2 configuration file locations

Different distributions might have the config file in a different location. Try looking for one of these:

/etc/apache2/httpd.conf
/etc/apache2/apache2.conf
/etc/httpd/httpd.conf
/etc/httpd/conf/httpd.conf

How to stop serving the “.git” directory? (Nginx)

Add this to your configuration file:

location ~ /\.git {
    deny all;
}

Did not work? Try this instead:

http {
  server {
    location ~ /\.git {
      deny all;
    }
  }
}

Please note that this statement needs to come before your main location block. Reload your server config or restart.

Testing

Simply create a directory called .git in your web root, and inside it a text file called test, and inside it some arbitrary text like “oh no”, and try accessing it. Before applying the changes you should simply see “oh no”, after the changes you should get a 403 permission denied.

Got issues or suggestions? Let me know in the comments!