Set PHP configuration options with Nginx

Posted April 26th, 2015 in Nginx Web Server and PHP

There may be times you need to set specific PHP options for a virtualhost on Nginx, for example adding an automatically prepended file to all pages. This post shows how to do this.

PHP auto_prepend_file example with Nginx

Let's say you have a setting like this to make all .php files be parsed as PHP:

server {
  ... configuration options ...
  location ~ \.php$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_param	QUERY_STRING		$query_string;
    fastcgi_param	REQUEST_METHOD		$request_method;
    fastcgi_param	CONTENT_TYPE		$content_type;
    fastcgi_param	CONTENT_LENGTH		$content_length;
    ... etc etc ...
  }
}

Simply add this in with the other fastcgi_param values:

fastcgi_param PHP_VALUE auto_prepend_file=/path/to/prepend.php;

The above example will automatically prepend the file at /path/to/prepend.php to all files that have a .php extension and parse them as PHP.

You should be able to set any other PHP value that can be configured outside the php.ini file in the same way, changing auto_prepend_file to the confguration name, and /path/to/prepend.php to the configuration value.