Nginx Configuration for Symfony

Recently when setting up a Symfony project on an Nginx powered server I found the Example configuration script found on the Nginx wiki for Symfony didn’t fully work as expected.

  1. If you added a slash to the end of the url when requesting backend.php or frontend_dev.php or similar caused the page not be found, even though under Apache this works fine and goes to the correct place. Which seemed to be caused by the script_name server param.
  2. GET parameters were not getting passed to Symfony. Caused by the arguments been removed during the try_files request.

So I modified the example config to produce the following, which as far as I can tell works exactly the same as the default .htaccess file does under Apache.

server {
        server_name example.org *.example.org;
        server_tokens off;
        root /home/example_org/www/web;
        index index.php index.html index.htm;
 
        access_log  /var/log/nginx/www.example.org-access_log;
        error_log  /var/log/nginx/www.example.org-error_log;
 
        location / {
                try_files $uri /index.php?$args;
        }
 
        location /sf/ {
          root /var/www/symphony/lib/vendor/symfony/data/web/;
        }
 
		location ~ \.php($|/) {
                set  $script $uri;
                set  $path_info "";
 
                if ($uri ~ "^(.+\.php)(/.*)") {
                        set  $script     $1;
                        set  $path_info  $2;
                }
 
                fastcgi_pass   127.0.0.1:9000;
                include        fastcgi_params;
                fastcgi_param  PATH_INFO         $path_info;
                fastcgi_param  SCRIPT_FILENAME   $document_root$script;
                fastcgi_param  SCRIPT_NAME       $script;
        }
 
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}

If you do find any problems with the above config just use the comments section below.

  • Mentalow

    Hi,

    Does it work on Symfo 2 ?
    If not, do you have any idea to make it work ?

    Thanks =)

    • Seb Dangerfield

      Yes it should work fine symfony 2. Although you will need to swap the line:
      try_files $uri /index.php?$args;
      for:
      try_files $uri /app.php?$args;

      due to a change in the name of the front controller script.