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
- 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.
- Use an .htaccess File (Apache): If your website uses Apache, create or edit a file named
.htaccessin 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|docxwith the actual file extensions you want to block. This tells Apache to deny access directly to those files. - 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|docxwith the file extensions you want to block. Restart Nginx after making changes:sudo systemctl restart nginx - 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.
- PHP Example: You can read a file using
- 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.
- Important Considerations:
- File Extensions: Be careful when specifying file extensions. Blocking common ones like
.jpgor.pngmight 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.
- File Extensions: Be careful when specifying file extensions. Blocking common ones like

