Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Enable PHP OPcache with Nginx and PHP-FPM (and Verify It Works)

Enable OPcache in PHP-FPM—not just CLI PHP—then connect Nginx to the right pool, restart workers and verify the cache through a web request.
Length10 min Posted Quest giverVGSources Team

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Enable OPcache in the PHP configuration used by PHP-FPM, not just the command-line (CLI) configuration. Confirm that Nginx forwards requests to that FPM pool, restart the matching PHP-FPM workers, and verify the result through a temporary web diagnostic. Nginx itself does not turn OPcache on; PHP loads the extension and keeps compiled bytecode in shared memory.

What OPcache does in an Nginx/PHP-FPM stack

OPcache is a PHP extension that stores precompiled script bytecode in shared memory. Without it, PHP repeatedly reads, parses and compiles PHP files as requests arrive. With it, workers can reuse compiled bytecode until a script is invalidated or the cache is reset. This reduces repeated compilation work, but it does not cache complete HTTP responses and it does not replace application, database or Nginx response caching.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The request path matters when enabling it:

  • A browser sends an HTTP request to Nginx.
  • Nginx passes matching PHP requests to a FastCGI endpoint.
  • PHP-FPM accepts the request in a worker pool.
  • The PHP-FPM SAPI loads its own PHP configuration and OPcache settings.

Because PHP-FPM and CLI are separate SAPIs, a setting shown by php in a shell can differ from the setting used by a web request. The browser-facing FPM SAPI is the authority for this task.

Before changing anything: identify the FPM installation

You need shell access, permission to edit the PHP-FPM configuration, permission to restart or reload the service, and an Nginx server block that sends PHP files to that FPM pool. Record the PHP version and the FPM socket or TCP endpoint before editing files; systems commonly run more than one PHP version.

Use CLI commands as an initial inventory

php --ini
php -m | grep -i opcache

php --ini prints the CLI SAPI’s loaded file and scanned directory. php -m shows whether the CLI process can load an OPcache module. These commands are useful clues, not proof that the website is configured correctly. A different FPM binary, version or scanned directory may be in use.

Check the FPM SAPI directly

Create a short, temporary diagnostic file inside the document root served by the same Nginx server block as the application:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
header('Content-Type: text/plain; charset=utf-8');

if (function_exists('opcache_get_status')) {
    var_export(opcache_get_status(false));
} else {
    echo "OPcache functions are unavailablen";
}

phpinfo();

Open that file through the real hostname, not through a CLI command or a different virtual host. The output identifies the FPM PHP version, the loaded configuration file, additional scanned .ini files, and OPcache values. If the endpoint exposes environment details, restrict it temporarily by IP or a web-server rule and delete it immediately after verification.

Confirm that OPcache is loaded once

If OPcache was built as a shared extension, PHP documents loading it with a zend_extension directive:

zend_extension=/full/path/to/opcache.so

The path must be the actual module path for the FPM PHP installation. On packaged Linux systems, vendors commonly ship an OPcache .ini fragment that already loads the extension. Inspect the FPM SAPI’s “Additional .ini files parsed” list in the web diagnostic before adding a line. Loading the same extension through two files can produce a duplicate-load warning or prevent PHP from starting.

Do not assume that a successful CLI module check means FPM has the extension. Conversely, do not add a second zend_extension line merely because you cannot find it in the CLI configuration; inspect the web SAPI first.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set a conservative OPcache baseline for PHP-FPM

Place the directives in the php.ini file used by FPM or in an OPcache-specific .ini file that FPM scans. PHP-FPM uses normal PHP php.ini syntax. The following baseline is suitable for many applications and deliberately keeps automatic freshness checks enabled:

; Put this in the php.ini or OPcache .ini file read by PHP-FPM
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.validate_timestamps=1
opcache.revalidate_freq=2
opcache.save_comments=1

The PHP manual currently lists these defaults: 128 MB for opcache.memory_consumption, 8 MB for opcache.interned_strings_buffer, 10,000 for opcache.max_accelerated_files, enabled timestamp validation, and a two-second revalidation interval. They are configuration defaults, not a promise of a particular percentage performance gain.

What each directive controls

Directive Purpose Baseline and decision
opcache.enable Enables OPcache for normal PHP requests. 1 for a web application. Verify that FPM reports it enabled.
opcache.memory_consumption Allocates shared memory for cached bytecode. 128 MB is the current PHP default. Increase only when status shows a capacity problem and the host has memory available.
opcache.interned_strings_buffer Reserves shared memory for interned strings. 8 MB is the current PHP default. Larger codebases may need a measured adjustment.
opcache.max_accelerated_files Sets the approximate limit of scripts that can be cached. 10000 is the current PHP default. Choose a value that covers the application’s PHP file count.
opcache.validate_timestamps Allows OPcache to notice changed source files. 1 during development and for deployments that do not perform an explicit reset.
opcache.revalidate_freq Sets the timestamp-check interval in seconds when validation is enabled. 2 seconds is the current default. Use 0 when development requires a check on every request.
opcache.save_comments Preserves PHP comments and docblocks in the compiled representation. Keep 1 unless the application is known not to use annotations. Disabling comments can break frameworks and tools that parse docblocks.

Memory and file-count settings are capacity limits, not speed settings by themselves. Watch OPcache status after the application has warmed up. If the cache is full, raise capacity only after checking the host’s available RAM and the FPM worker count; every worker uses the shared OPcache segment, but the overall PHP process footprint still matters.

Choose timestamp validation for your release model

Development and frequently edited sites

Keep opcache.validate_timestamps=1. OPcache checks for changed scripts at the interval set by opcache.revalidate_freq. Set the interval to 0 when every request must detect edits immediately; otherwise, a short interval such as the two-second default avoids checking the filesystem more often than necessary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Production with an explicit invalidation step

A production deployment that atomically replaces the complete application tree may set opcache.validate_timestamps=0 to remove filesystem timestamp checks. This is safe only if every release resets OPcache or restarts the PHP-FPM workers after the new files are in place. PHP documents that, with validation disabled, changed files do not take effect until an explicit invalidation or worker restart occurs.

Do not disable validation while relying on an informal “it usually updates” process. A forgotten reset can leave old code running indefinitely, producing a split deployment in which some files are new and others remain cached.

Configure Nginx to pass PHP requests to the intended FPM pool

Nginx does not enable OPcache. Its job here is to pass PHP requests to FastCGI and provide PHP-FPM with the correct script filename. A minimal location looks like this:

location ~ .php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    fastcgi_index index.php;
}

Replace the example socket with the endpoint exposed by the installed FPM pool. A pool may instead listen on a TCP address such as 127.0.0.1:9000:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
fastcgi_pass 127.0.0.1:9000;

The PHP version and socket filename in these examples are placeholders. Inspect the pool configuration and the service status to find the live value. The important parameters are:

  • fastcgi_pass selects the FPM socket or TCP listener.
  • fastcgi_param SCRIPT_FILENAME maps the request to the file on disk.
  • fastcgi_index identifies the default index script for directory requests.
  • include fastcgi_params supplies the standard request parameters expected by FPM.

Keep the PHP location narrow enough that Nginx cannot send arbitrary non-PHP files to FPM. Verify that $document_root$fastcgi_script_name resolves inside the intended document root and that the server block serving the diagnostic is the one users actually reach.

Apply the configuration safely

  1. Edit the FPM php.ini or scanned OPcache .ini file and save a backup of the previous version.
  2. Confirm that the Nginx fastcgi_pass endpoint matches the PHP-FPM pool you intend to use.
  3. Test Nginx syntax before reloading it:
    nginx -t
  4. Reload Nginx after a successful test so the server uses the verified FastCGI configuration.
  5. Restart, or perform a worker restart through the host’s service manager, for the matching PHP-FPM service. A worker restart is the reliable way to apply process-level OPcache configuration changes.
  6. Open the diagnostic URL again and confirm that the FPM SAPI reports the new values.

The exact service-unit name varies with the installed PHP version and operating system. Use the service manager’s listing or the package’s documented unit name rather than restarting an unrelated PHP version. Reloading Nginx alone does not reload PHP-FPM’s OPcache segment.

Verify OPcache from a real web request

Use phpinfo() or opcache_get_status() through the same hostname and server block that serves the application. Check all of the following:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • opcache.enable is 1.
  • opcache_get_status() reports an enabled cache and a nonzero memory allocation.
  • The reported memory size, accelerated-file limit and revalidation interval match the FPM configuration.
  • The PHP version and loaded configuration file are the ones expected for this site.
  • The request reaches the intended FPM pool and socket, rather than another PHP version.

After verification, request a harmless application page to warm the cache. Inspect Nginx and PHP-FPM logs for FastCGI connection failures, missing files or script-filename errors. Delete the diagnostic endpoint when finished; a public phpinfo() page reveals paths, modules, environment variables and other information useful to an attacker.

Development and production settings compared

Concern Development profile Production profile
Detecting edits opcache.validate_timestamps=1. Either keep validation enabled or disable it only with a mandatory reset/restart step.
Recheck interval 0 for immediate checks, or a short interval such as 2 seconds. A longer interval can reduce checks; disabled validation requires explicit invalidation.
Deployment invalidation Automatic timestamp checks. Restart FPM workers or call a controlled invalidation operation after each release.
Comments and annotations Keep opcache.save_comments=1. Keep it enabled unless compatibility has been proven otherwise.
Verification Inspect the web SAPI after configuration edits. Include a post-deploy status check and log review.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

CLI reports OPcache, but the browser reports it disabled

CLI and FPM can load different php.ini files, extension directories and PHP versions. Reopen the temporary web diagnostic and check its “Loaded Configuration File” and scanned .ini list. Add or change the directive in the FPM configuration, then restart the matching FPM service. Do not treat php -m as a web verification.

Source changes do not appear

Check opcache.validate_timestamps and opcache.revalidate_freq in the FPM output. If validation is enabled, wait for the configured interval or use 0 during development. If validation is disabled, reset OPcache or restart the FPM workers after the release. Also confirm that Nginx points to the FPM pool whose workers you restarted.

Nginx returns 502 Bad Gateway

A 502 generally means Nginx cannot reach the FastCGI endpoint. Verify that the FPM service is running, that the socket path or TCP address in fastcgi_pass is correct, and that the Nginx worker has permission to access a Unix socket. Check both Nginx’s error log and the PHP-FPM service log. A configuration change to OPcache will not fix a dead or mismatched socket.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The wrong script executes, or the setup presents a security risk

Inspect the resolved SCRIPT_FILENAME and document root. A malformed path can produce “file not found” errors or route requests outside the intended application tree. Keep the PHP location restricted to the files that should be executable, and test a known application script through the production server block.

Framework annotations stop working

Restore opcache.save_comments=1 and restart FPM. PHP warns that discarding comments can break frameworks and tools that parse docblock annotations. Re-test the affected routes after the worker restart.

The cache fills or scripts are not retained

Use opcache_get_status() to inspect available memory, wasted memory and the number of cached scripts. If the application approaches the accelerated-file limit or shared-memory capacity, count the deployed PHP files, review unused code, and increase the relevant limit only after confirming adequate system memory. Restart FPM after changing capacity directives.

Operational checklist for every change

  • Identify the FPM PHP version, loaded configuration file and scanned directories through a web request.
  • Confirm OPcache is loaded once; avoid duplicate zend_extension entries.
  • Set directives in the FPM configuration, not only the CLI configuration.
  • Choose timestamp validation based on whether your release process performs an explicit reset.
  • Verify the Nginx socket or TCP endpoint and the SCRIPT_FILENAME mapping.
  • Run nginx -t before reloading Nginx.
  • Restart the matching PHP-FPM workers after OPcache configuration changes.
  • Check status through the real web hostname and remove diagnostic files immediately.
  • Review FastCGI and FPM logs after deployment.

OPcache is not Nginx response caching

OPcache stores compiled PHP bytecode inside PHP’s shared memory. Nginx’s fastcgi_cache stores HTTP responses and has separate cache keys, expiration rules, bypass conditions and invalidation risks. Enabling one does not enable the other. Configure response caching only after the application can safely serve cached responses, particularly for sessions, authentication and personalized pages.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bottom line

To enable OPcache with Nginx and PHP-FPM, load the extension once, set the directives in the FPM SAPI’s configuration, route PHP requests to the correct FPM pool, test Nginx, restart the PHP-FPM workers, and verify the result from a real browser request. Keep timestamp validation on while developing. If production disables it, make an OPcache reset or FPM restart an unavoidable part of every deployment.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.