Version control systems like Git are very important for software development. But if they are not properly secured, they can leak sensitive information. Many web developers accidentally leave the .git directory accessible on live websites, which lets anyone download and see the repository. This guide will show you how to block access to the .git directory on Apache and Nginx web servers.
Apache: Using .htaccess
- Find the .htaccess file: Go to the root directory of your website or the directory where the .git folder is.
- Edit the .htaccess file: Open .htaccess in a text editor. If it doesn’t exist, create it.
- Block access to the .git directory: Add these lines to your .htaccess file:
# Block access to .git directory <Directory ~ "\.git"> Order allow,deny Deny from all </Directory>
- Save and close the file: After adding the lines, save and close the .htaccess file.
- Restart the Apache server: The changes take effect immediately, but it’s good to restart the server to make sure it picks up the changes.
Nginx
- Find the Nginx configuration file: The Nginx configuration file is usually located in /etc/nginx/ or /usr/local/nginx/conf/. The main file is often named nginx.conf.
- Edit the configuration: Open nginx.conf or the correct server block file in a text editor.
- Block access to the .git directory: Add this block inside the server block to deny access to the .git directory:
# Block access to .git directory RedirectMatch 403 /\.git
This configuration blocks access to any path containing .git and returns a 403 Forbidden HTTP status.
- Save and close the file: After making changes, save and close the file.
- Reload the Nginx configuration: To apply the changes, reload the Nginx configuration with:
sudo nginx -s reload
Testing
After applying the changes, make sure they work as expected:
- Try accessing the .git directory: In your web browser, go to http://yourdomain.com/.git/ or any file inside that directory.
- Expect a 403 response: If everything is set up correctly, the server should return a “403 Forbidden” response.
Conclusion
Security is very important for web servers, especially with version control systems like Git that can accidentally expose sensitive information. Always make sure that directories like .git are blocked from public access. Regularly check your web server configurations for any potential security risks.
1 Comment
This doent worked for me on an Apache in Ubuntu.
This worked:
RewriteEngine On
RewriteRule ^\.git/ – [F]