title: Symfony - how to serve image from controller with nginx's X-Accel-Redirect
body: <p>I want to serve protected images to authorized users only. So therefore I'm using <code>BinaryFileResponse</code> within controller and it works fine. However, I would like to use the Nginx's XSendfile (X-Accel-Redirect). I've done the same steps as explained in Nginx's <a href="https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/" rel="nofollow noreferrer">documantation</a>.</p>
  
  <p>Also I've added the <code>BinaryFileResponse::trustXSendfileTypeHeader();</code> to controller. But now I'm keep getting a 404 response.</p>
  
  <p>Here are my configs and code:</p>
  
  <p>Nginx:</p>
  
  <pre><code>server {
      listen 80;
      listen 443 ssl http2;
      server_name symfony.app;
      root "/home/vagrant/Sites/Symfony/web";
  
      index index.html index.htm index.php app.php app_dev.php;
  
      charset utf-8;
  
      location / {
          try_files $uri $uri/ /app.php?$query_string;
      }
  
      location /images/ {
          internal;
          alias   /home/vagrant/Sites/Symfony/app/media/images/listings/4/;
      }
  
      client_max_body_size 100m; 
  
      # DEV
      location ~ ^/(app_dev|app_test|config)\.php(/|$) {
          #fastcgi_split_path_info ^(.+\.php)(/.+)$;
          fastcgi_split_path_info ^(.+\.php)(/.*)$;  # allows trailing slash after app_dev.php/
          fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
          include fastcgi_params;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  
          fastcgi_intercept_errors off;
          fastcgi_buffer_size 16k;
          fastcgi_buffers 4 16k;
      }
  
      # PROD
      location ~ ^/app\.php(/|$) {
          fastcgi_split_path_info ^(.+\.php)(/.+)$;
          fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
          include fastcgi_params;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  
          fastcgi_intercept_errors off;
          fastcgi_buffer_size 16k;
          fastcgi_buffers 4 16k;
          internal;
      }
  
      location ~ /\.ht {
          deny all;
      }
  
      ssl_certificate     /etc/nginx/ssl/symfony.app.crt;
      ssl_certificate_key /etc/nginx/ssl/symfony.app.key;
  }
  </code></pre>
  
  <p>Symfony Controller:</p>
  
  <pre><code>public function getPictureAction($id)
      {
          $filePath = 'media/images/listings/4/';
          $path = $this-&gt;get('kernel')-&gt;getRootDir() . '/' . $filePath . $id;
  
          BinaryFileResponse::trustXSendfileTypeHeader();
  
          $response = new BinaryFileResponse($path);
  
          $response-&gt;headers-&gt;set('Content-Type', 'image/jpg');
          $response-&gt;setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
          return $response;
      }
  </code></pre>
  
  <p>So, going to <strong>http://symfony.app/images/1.jpg</strong> should return an image, but got a 404.</p>