Nginx configuration question for .git directories
We got a spam email today from someone at websafety.ninja. He claims our /.git directory is available to the public through our URL. I went to it and got the 404 error like we have setup on our nginx server, but when I went to subdirectories like /.git/config, /.git/objects, etc. the browser downloaded those files. The good thing is that our actual git repository is not on this site and the files that were actual downloaded contain information for the repository of the open source Wordpress-core repository on GitHub. This is an older project so it might have just been from a blank Wordpress install while the site was in development but clearly none of our source code is at risk.
However, I find it odd that I'm able to download files like that even though I have this code block in our /etc/nginx/sites-available/example.com folder
location ~ /\.git {
return 404;
}
As I mentioned before, I do get the 404 page when I just go to /.git but when I go to it's sub files it downloads that file. Am I missing something in the location line?
I also tried with the same result
location ~ /\.git {
deny all;
}
4 Replies
From what I understand the code snippets provided will only block access to the one directory, but not files or subdirectories at that location. You'll need to either ad a line for each directory and file or use regex to make sure all files are denied.
There's an official NGINX post on regex that includes a regex tester here:
https://www.nginx.com/blog/regular-expression-tester-nginx/
There's an online regex tester here:
https://www.regexpal.com/94055
From a bit of testing I did, I think the following regex will work to block everything in the /.git directory:
\/\.git\/?.*
Thanks! Those testers should come in handy. The weird thing that is still happening though is that if I got to a file in that directory e.g. /.git/config it downloads that file from the browser and then redirects back to the URL /.git. So it almost seems like the .git directory and it's files are denied access in the browser but it still downloads those files and I'm not sure what I need to add to my nginx server block to deny those downloads from the browser
You could simply change:
location ~ /\.git {
return 404;
}
to
location /.git {
return 404;
}
With the ~
it's a "regular expression" location and needs to cover all possible paths in its expression.
Without the ~
it's a "prefix" location and will match /.git
and everything below (both files and directories). A bit easier and more automagic. The dot character has no special meaning in prefix locations either, so doesn't need to be backslashed.
https://nginx.org/en/docs/http/ngx_http_core_module.html#location