How to configure Nginx to pass PHP-FPM environment variables?

To configure Nginx to pass PHP-FPM environment variables, you need to make changes to the Nginx configuration file. You can follow these steps:

  1. Open the Nginx configuration file for your website. The file is usually located in the /etc/nginx/sites-available/ directory and could be named something like example.com or default.

  2. Within the server block, find the location ~ \.php$ block. This is the section responsible for handling PHP files.

  3. Add the fastcgi_param directive to pass the PHP-FPM environment variables. For example, if you want to pass the APP_ENV environment variable, add the following line inside the location ~ \.php$ block:

    fastcgi_param APP_ENV production;

    You can add multiple fastcgi_param directives as needed for other variables.

  4. Save the file and exit.

  5. Test the Nginx configuration to ensure it is valid, and reload or restart Nginx.

    sudo nginx -t sudo systemctl reload nginx

That's it! Now, Nginx will pass the specified environment variables to PHP-FPM when processing PHP files. You can access these variables in your PHP scripts using the $_SERVER superglobal array.