How can I protect a credentials file using .htaccess


I am working on an old project.

The database credentials are stored as JSON in web root in a file like .my_secret and configurations are stored in .my_config – A PHP script reads these files and uses the data for connecting to the database and retrieving other settings.

If someone tries to access this file, I want to throw a 404 error, file not found.

How can I do this using only .htaccess? I don’t want to use .htpasswd

I tried to move the files outside the web root, but I encountered an open_basedir restriction in effect

>Solution :

You can simply create a rewrite rule for these files that points to a 404 file:

ErrorDocument 404 /404.php

RewriteRule ^(\.my_config|\.my_secret) 404.php [L,nc]

In the 404.php file you can output 404 headers like this:

header('HTTP/1.0 404 Not Found');

Leave a Reply Cancel reply