titiyoyo
titiyoyo

Reputation: 942

NGINX -- serving static files on an symfony2 website

I'm trying to setup a virtual location in nginx in order to serve large static files from a directory. The main app is a symfony2 program.

What I would like to do is having an url where you could specify a filepath within a GET parameter, that way nginx could serve the file directly to the client.

In my example the location would be /getfile

Here's my config so far

server
{
    listen                                              80;
    server_name                                         website_url;
    set                                                 $path_web /myapp/webdir;

    client_max_body_size                                200m;   

location /getfile {             
    root /path_to_dir;
        if ($args ~ ^oid=(.*+)) {
          set $key1 $1;
          rewrite ^.*$  $key1;
        }   
    }

location ~ \.php($|/)
{
      set  $script     $uri;
      set  $path_info  "";

      if ($uri ~ "^(.+\.php)(.*)") {
          set  $script     $1;
          set  $path_info  $2;
      }


      fastcgi_pass   unix:/tmp/php-fpm.sock;
      fastcgi_index  index.php;
      fastcgi_param  SCRIPT_FILENAME  $path_web$script;
      fastcgi_param  SCRIPT_NAME      $script;
      fastcgi_param  PATH_INFO        $path_info;

      include   /etc/nginx/conf.d/fastcgi.conf;
}


    root                                                    $path_web;
    index                                                   app.php app_dev.php;

    location / 
    {   
    set $idx_file app.php;

    if ($args ~ debug=true) {
        set $idx_file app_dev.php;
        }

        if ( !-f $request_filename) {
    rewrite ^(.*)$ /$idx_file last; 
        }
    }

    location ~ /\.ht
    {
    deny                 all;
    }



    # logs path
    access_log                                          /path_to_logdir/access.log main;
    error_log                                           /path_to_logdir/error.log;
}

Upvotes: 1

Views: 1889

Answers (2)

Tom Tom
Tom Tom

Reputation: 3698

I'm adding my answer as there is no definite one. I would rather use try_files, so it would look something like that.

location /my/path {
  # try to serve file directly, fallback to rewrite
  try_files $uri $uri @rewrite;

}
location @rewrite {
  rewrite ^/(.*)$ /app.php/$1 last;
}

The server will then first look for the image at the given path and if not found fallback to app.php. It is much better than ifs and elses as it should never fallback to app.php.

Upvotes: 1

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42789

Though I'm not sure if this will work or not, but you've used an if and a set and a rewrite, too many un-needed things, I would try this

location /getfile?oid=(.*) {             
      rewrite ^ /path/$1;
}

Upvotes: 0

Related Questions