Search code examples
linuxsecuritynginxwebserver

Best way to keep files on web server secure


Context: I have some files on linux web server for example create_db.txt. They are using in my php scripts but now everyone can watch them by the direct link

http://url/create_db.txt

What is the right way to deny access to this files and still have opportunity to wright and read informations in them from php scripts. Thanks.


Solution

  • If you are using Apache you could restrict access to specific files by adding an .htaccess file in the web root:

    <Files create_db.txt>
    Order allow, deny
    Deny from all
    </ Files>
    

    The Files section above would restrict access for all users to the create_db.txt file.

    Running nginx the same could be achieved by adding the following to your configuration:

    location ^~ /create_db.txt {
      deny all;
    }
    

    Like stated in the other answer you really should consider moving the file to a directory outside of your webroot. Of course the webserver must be able to access this folder. This can be done by setting the correct permission on the folder and perhaps by changing the owner to that of the webserver. Something like this:

    mkdir -m 755 -p /path/outside/webroot
    mv create_db.txt /path/outside/webroot
    chown -R <user>:<group> /path/outside/webroot