Get a Pentest and security assessment of your IT network.

Cyber Security

Prevent Direct File Access

TL;DR

Stop people from directly downloading files by typing their URL into a browser. Let your server-side scripts still access them normally.

Solution Guide

  1. Understand the Problem: When you put files on a web server, anyone who knows the file’s exact location (URL) can usually download it directly. This isn’t always what you want – especially for sensitive data or files meant to be processed by your website first.
  2. Use an .htaccess File (Apache): If your website uses Apache, create or edit a file named .htaccess in the directory containing the files you want to protect. Add these lines:
    <FilesMatch ".(pdf|zip|doc|docx)"
        Require all denied
    </FilesMatch>

    Replace pdf|zip|doc|docx with the actual file extensions you want to block. This tells Apache to deny access directly to those files.

  3. Configure Nginx (if applicable): If your website uses Nginx, edit your server configuration file (usually in /etc/nginx/sites-available/). Add a location block like this:
    location ~* .(pdf|zip|doc|docx)$ {
        deny all;
        return 403;
    }
    

    Again, replace pdf|zip|doc|docx with the file extensions you want to block. Restart Nginx after making changes:

    sudo systemctl restart nginx
  4. Server-Side Script Access: Your server-side scripts (e.g., PHP, Python, Node.js) will still be able to access the files because they run *as* the webserver user and are not subject to these restrictions.
    • PHP Example: You can read a file using file_get_contents() or similar functions within your PHP script.
    • Python Example (Flask): Use Python’s file handling methods within your Flask application to access the files.
  5. Check Your Configuration: After implementing these changes, test thoroughly:
    • Try accessing a blocked file directly in your browser. You should get a 403 Forbidden error (or similar).
    • Make sure your server-side scripts can still read and process the files as expected.
  6. Important Considerations:
    • File Extensions: Be careful when specifying file extensions. Blocking common ones like .jpg or .png might break images on your site if you aren’t careful.
    • Security Best Practices: This method is a good first step, but it’s not foolproof. For highly sensitive data, consider more robust security measures like user authentication and authorization.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation