In this guide, I will show you how to block access to .git folder.

When you initialize or deploy the Git application, it creates a .git folder that contains sensitive information. If .git folder is accessible over the Internet, it can potentially leak your data.

Here is an example of  data leaking with a security vulnerability scanner like gitjacker

Gitjacker downloads git repositories and extract their contents from sites where the .git directory has been mistakenly uploaded. It will still manage to recover a significant portion of a repository even where directory listings are disabled.

Webservers allow you to block certain files or directories under your document root from being accessed over the web.

Nginx

To block access to .git folder, add the following to your Nginx server entry.

location ~ /\.git {
deny all;
}

Now restart Nginx.

systemctl restart nginx

Apache

To block access to .git folder, add the following to your httpd.conf file.

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

Now restart the Apache.

RHEL & Centos

systemctl restart httpd

Ubuntu / Debian

systemctl restart apache2

htaccess rule

Open your website root directory and place the next to .htaccess file:

RedirectMatch 404 ^/\.git

The rule will take effect as soon as you save your changes.