Home > Back-end >  Symfony - Redirect file url to controller
Symfony - Redirect file url to controller

Time:09-24

I made a blog on Symfony and i have implemented a upload function to attach files to posts. I want to deny direct access to files (like this : http://mysite/456/uploads/test.pdf) so i made a controller to catch url

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class checkAccessAttachmentController extends AbstractController
{
    /**
     * @Route("/uploads/{post}/{file}", requirements={"file"="[0-9a-zA-Z_.]*"})
     */
    public function index(Post $post, string $file): Response
    {
        //TODO Check role / Blog post data / whatever
        //If ok : access file ok
        dd($file);
    }
}


URL like this is ok : https://mysite/uploads/14543/documentpdf

However, It doesn't work when URL have a dot (in the file name typically) Something like this doesn't work : https://mysite/uploads/14543/document.pdf the file is automatically downloaded, controller is not triggered.

I think there is a little thing to specify in route parameters, but i don't know what.

Last precision : I have installed Symfony on Apache, with the symfony/apache-pack. So a htaccess have been created and could be the reason of the issue

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php

# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options  FollowSymlinks

# Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve
# to the front controller "/index.php" but be rewritten to "/index.php/index".
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the index.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$0 ^(/. )/(.*)::\2$
    RewriteRule .* - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by Apache
    RewriteCond %{HTTP:Authorization} . 
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/index.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} =""
    RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    # Rewrite all other queries to the front controller.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ %{ENV:BASE}/index.php [L]

</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 307 ^/$ /index.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

Thanks for your help

CodePudding user response:

There's a part in the htaccess file, at the end of the <IfModule mod_rewrite.c> that says:

# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
# Rewrite all other queries to the front controller.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ %{ENV:BASE}/index.php [L]

you could comment out or delete that line, but it will also affects all the other files (png, jpg, css, js, etc...) or you could do an intricate and complicated RewriteCond that affects only the pdfs on a specific directory and hope that the rule survives a server migration.

Or you can do it the easy way.

The Easy Way

  • Modify your upload controller so the files are saved in a path outside the public directory, or even another storage medium.
  • Save the metadata (path, filename, mimetype, etc) of the file in the BD linked to the post. Also, generate an id or hash with uniqid, md5, uuid, whatever, and save it in the metadata to avoid collisions in the directory and/or obfuscate the file even more.
  • In your download controller, ask for the file id you created previously and serve it with the BinaryFileResponse class instead.

That last point would be something like this:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;

class checkAccessAttachmentController extends AbstractController
{
    /**
     * @Route("/uploads/{post}/{file_hash}", requirements={"file"="[0-9a-zA-Z_.]*"})
     * @Entity("file", expr="repository.findByHash(file_hash)")
     */
    public function index(Post $post, FileEntity $file): BinaryFileResponse
    {
        //TODO Check if $file belongs to post / role / Blog post data / whatever
        //The @Entity in the annotation handles the 404 if the id doesn't exists
        if ($check){
            $response = new BinaryFileResponse($file->getFullPath());
            $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file->getFilename()); //DISPOSITION_ATTACHMENT forces download, even if browser can open the pdf. Use DISPOSITION_INLINE to let the browser decide
            return $response;
        } else {
            throw new AccessDeniedHttpException();
        }
    }
}
  • Related