Overview
Apache allows you to block certain files or directories under your document root from being accessed over the web. This is very beneficial if, for example, you have an application version controlled by Git. Odds are you do not want any of the files under .git to be accessed, for various security reasons. Ideally, you wouldn’t allow directories like these to exist under your document root, however, in the real world these things can happen and are beyond your control.
This technique isn’t solely for Git. It can be used for any type of file or directory you want to block access to.
Regex
Although this scope of this article is Git, if you are up to speed with your regex-fu, you can protect any directory. Of course, as mentioned above, the recommended approach would be to not have anything you wouldn’t want expose publicly located under your document root.
Protecting Git Directories
The configuration that protects your directory can be applied in a number of places. It depends on your access to the Apache (.htaccess) or whether you want the protection to be globally (httpd.conf or apache2.conf) or for an individual vhost. In this example, I will write into my Apache configuration to apply globally across all vhosts.
- Open the Apache configuration file into a text editor.
CentOS \ Red Hatvi /etc/httpd/conf/httpd.conf
Ubuntu
vi /etc/apache2/apache2.conf
- Ensure the Rewrite engine is enabled by adding the following line.
RewriteEngine on
- Add the following to the configuration file.
<DirectoryMatch "^\.git$amp;"> Order Deny,Allow Deny from all </DirectoryMatch>
- Save your changes and exit the text editor.
- Reload the Apache configuration file to apply your changes.
CentOS \ Red Hatservice httpd reload
Ubuntu
service apache2 reload
Summary
With your git files protect, anyone who attempts to access them will receive a 403 error (not authorized). This should allow you to sleep a little better at night know it will be a lot more difficult for someone to access them.