We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Prevent direct access to file

Hello! Began to develop recently on phalcon, there is a direct link to the txt file. Is it possible to restrict access to it using routes. For example i have https://example.com/report/report1.txt

edited Feb '19

Usually my directory structure is something like:

apps/
data/
common/
public/

Everything that is inside /public/ folder is web accessible, but everyting within the root level is not. So, keep sensitive files within root or "deeper". In the root I have .htaccess file for Apache servers, else its done in nginx config file. Here is apache version and the portion of .htaccess file:

Options -Indexes

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Forward to public/ (new short version)
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

With this script im forwarding all web requests to the /public/ folder, within that folder i habe index.php file that bootstraps my application.

If you want to restrict access to specific directory and dont do anything Phalcon specific, here are some tricks with .htaccess:

https://www.opentechguides.com/how-to/article/apache/115/htaccess-file-dir-security.html

edited Feb '19

You'll need to add an .htaccess file to rewrite requests for files, to the main Phalcon index.php file. From there you can just add a route to handle the requests. Any request for report/xyz gets routed to ReportController::downloadAction with the parameter xyz. ReportController would then check access, and pass through the originally requested file data.

edited May '19

With nginx you can potentially use auth_request https://github.com/perusio/nginx-auth-request-module so you wouldn't need to implement any download actions in php, just some kind of auth request.