Last Updated: February 25, 2016
·
8.71K
· stephanebachelier

Setting environement variable for Symfony Nginx/PHP-FPM

The Symfony documentation gives a basic configuration available here:
http://symfony.com/doc/current/cookbook/configuration/web_server_configuration.html#nginx

Nginx configuration

Below is server block configuration taken from the Symfony documentation which just one addition to pass some environment variables to Symfony application :

server {
  server_name domain.tld www.domain.tld;
  root /var/www/project/web;

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

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

    location ~ ^/(app|app_dev|config)\.php(/|$) {
      fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_split_path_info ^(.+\.php)(/.*)$;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param HTTPS off;

      # now the interesting part
      fastcgi_param  SYMFONY__MY__VARIABLE  'my variable';
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

The interesting part as mention in the configuration is that you can forward some value using a custom name.

The variable mapping

The schema must be SYMFONY__NAME, where NAME can have some double underscores as separator.

NAME will translate to %name% variable in symfony, where double underscores will be replaced by a dot.

  • SYMFONY__VARIABLE -> %variable%
  • SYMFONY__MY__VARIABLE -> %my.variable%

Symfony configuration

Now in the symfony project available at /var/www/project/ you will any configuration file you where you may need the content of some environment variable.
Pretend I need the content of SYMFONY__MY__VARIABLE in the variable nothing_to_do in app/config/parameters.(yaml|php|xml|ini). It's your choice about the format.

I will use a yaml as it is easier to type:

# app/config/config.yaml 
[...]
parameters:
    nothing_to_do: %my.variable%
[...]

See the documentation about external variable configuration which does not cover Nginx:
http://symfony.com/doc/current/cookbook/configuration/external_parameters.html#environment-variables

As you may see it's quite simple but powerful.