How to Set PHP memory_limit in Nginx + PHP-FPM Configuration


12 views

In Apache with mod_php, setting memory limits was straightforward within VirtualHost or .htaccess:

php_value memory_limit 128M

With Nginx + PHP-FPM, we have several approaches to control memory limits:

Method 1: php.ini Direct Modification

The most universal method is editing php.ini:

memory_limit = 128M

Locate your active php.ini with:

php --ini

Method 2: Pool-specific Configuration

In your PHP-FPM pool configuration (typically in /etc/php-fpm.d/):

[www]
php_admin_value[memory_limit] = 128M

This allows different memory limits per pool.

Method 3: Per-directory .user.ini

Create a .user.ini file in your application root:

memory_limit=128M

This requires PHP >= 5.3 and needs the following php.ini setting:

user_ini.filename = ".user.ini"
user_ini.cache_ttl = 300

After making changes, always verify:

php -i | grep memory_limit
// Or create a test script:
<?php
phpinfo();
?>

When adjusting memory limits:

  • Monitor actual memory usage with tools like htop
  • Consider setting slightly higher than your peak usage
  • For memory-intensive applications, combine with opcache tuning
  • Changes require PHP-FPM service restart: systemctl restart php-fpm
  • Multiple configuration files may override each other
  • Cloud environments often have additional restrictions

When migrating from Apache with mod_php to Nginx with PHP-FPM, one common configuration challenge is setting PHP directives like memory_limit. Unlike Apache where you could simply add php_value directives in .htaccess or virtual host files, PHP-FPM requires a different approach.

The most straightforward method is to edit your php.ini file:

memory_limit = 128M

After making changes, restart PHP-FPM:

sudo service php-fpm restart

For more granular control, you can set memory limits per PHP-FPM pool. Edit your pool configuration (typically in /etc/php-fpm.d/):

[www]
php_admin_value[memory_limit] = 128M

Then restart PHP-FPM:

sudo systemctl restart php-fpm

Create a test PHP file with:

<?php
echo ini_get('memory_limit');
?>

Access this file through your web server to confirm the memory limit is applied correctly.

When dealing with PHP-FPM:

  • Changes in pool configuration override php.ini settings
  • Using php_admin_value instead of php_value prevents override by .user.ini files
  • For WordPress or similar CMS, you might also need to set WP_MEMORY_LIMIT

If your memory limit changes aren't taking effect:

  1. Verify which php.ini file is being loaded (create phpinfo() file)
  2. Check for multiple PHP-FPM pools running
  3. Look for .user.ini files that might override settings
  4. Confirm you're editing the correct PHP version's configuration