Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk10 min

How to Run PHP as FastCGI with Apache Using PHP-FPM

A practical, distribution-aware guide to connecting Apache with PHP-FPM through FastCGI, including virtual-host examples, socket permissions, validation steps and fixes for downloads, 404, 403, 502 and timeout errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run PHP through PHP-FPM and connect Apache to it with mod_proxy_fcgi. Apache remains responsible for HTTP, static files and virtual hosts; PHP-FPM manages PHP worker processes and listens on a Unix socket or TCP address. Your virtual host then forwards only PHP requests to that listener.

The reliable sequence is: install matching Apache and PHP-FPM packages, identify the pool’s listen endpoint, enable Apache’s proxy modules, add a PHP mapping that matches your document root, align socket permissions, validate the configuration, reload both services as needed, and test with a small script. The exact package and service names differ between distributions and PHP versions.

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.

What running PHP as FastCGI with Apache means

FastCGI keeps the PHP application process separate from Apache. A browser requests /index.php; Apache receives the HTTP request, applies the virtual-host and access rules, and passes the PHP request to PHP-FPM. FPM assigns it to an available worker, returns the generated response, and Apache sends that response to the browser. Requests for CSS, JavaScript, images and other static files can be served directly by Apache.

mod_proxy_fcgi is Apache’s FastCGI connector. The Apache Software Foundation describes it this way: “This module requires the services of mod_proxy and provides support for the FastCGI protocol.” The module does not start PHP or manage its workers; PHP-FPM does that job.

Unix socket or TCP listener

On one host, a Unix-domain socket is common because it avoids a network port and can be protected with filesystem ownership and mode bits. A typical value is /run/php/php-fpm.sock, although distributions often use a versioned path such as /run/php/php8.3-fpm.sock. A TCP listener, commonly 127.0.0.1:9000, is useful when Apache and FPM are separated or when your distribution’s pool is already configured that way.

Apache’s FastCGI backend path must correspond to the site’s document root. If the URL is /index.php and the document root is /var/www/example/public, the FastCGI mapping must expose that filesystem path to FPM rather than pointing at an unrelated directory.

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

Prerequisites and package installation

You need Apache 2.4 or a distribution-supported equivalent, PHP, PHP-FPM, and the Apache proxy modules that provide FastCGI support. Package names and service names vary by operating system and PHP release, so check your distribution’s package index before copying a command.

Debian or Ubuntu-style systems

sudo apt update
sudo apt install apache2 php-fpm
sudo a2enmod proxy proxy_fcgi setenvif

The FPM package may install a versioned service, for example php8.3-fpm, rather than a literal php-fpm unit. If Apache’s modules are split into a separate package on your release, install that package as well.

Fedora, RHEL or compatible systems

sudo dnf install httpd php-fpm
sudo systemctl enable --now httpd
sudo systemctl enable --now php-fpm

Some releases use a versioned FPM unit or require a separate Apache modules package. Substitute the service and package names supplied by your release.

Check the installed versions

apachectl -v
php -v
systemctl list-unit-files '*fpm*'

Do not assume that the command-line PHP version is the version Apache will use. Apache uses whichever FPM pool your virtual host references, and several PHP versions can coexist with different sockets.

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

Find and start the PHP-FPM listener

Open the active FPM pool configuration, usually the pool named www, and find its listen directive. Typical locations include a distribution’s pool.d directory, but the path is release-specific.

grep -R '^[[:space:]]*listen[[:space:]]*=' /etc/php /etc/php-fpm.d 2>/dev/null

You are looking for either a Unix socket:

listen = /run/php/php-fpm.sock

or a TCP endpoint:

listen = 127.0.0.1:9000

Start and enable the corresponding FPM service, replacing the unit name with the one installed on your host:

sudo systemctl enable --now php-fpm

Confirm that it is running and that the endpoint exists:

systemctl status php-fpm
ls -l /run/php/
ss -ltnp | grep 9000

A Unix socket should appear as a filesystem entry. A TCP listener should appear in the listening-socket list. If neither exists, fix FPM before changing Apache.

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.

Configure Apache to use PHP-FPM

Enable both mod_proxy and mod_proxy_fcgi. The first provides Apache’s proxy framework; the second speaks FastCGI. On systems with helper commands, the module command is commonly:

sudo a2enmod proxy proxy_fcgi setenvif

On other systems, verify that the modules are loaded by the distribution’s Apache configuration and restart or reload Apache after enabling them.

Unix-socket virtual host

Place a configuration like this in the site’s virtual-host file, changing the hostname, document root and socket to your values:

<VirtualHost *:80>
    ServerName example.test
    DocumentRoot /var/www/example/public
    DirectoryIndex index.php index.html

    <Directory /var/www/example/public>
        Require all granted
        AllowOverride None
    </Directory>

    ProxyPassMatch ^/(.*.php(/.*)?)$ unix:/run/php/php-fpm.sock|fcgi://localhost/var/www/example/public/

    <FilesMatch .(env|ini|log|sql)$>
        Require all denied
    </FilesMatch>
</VirtualHost>

ProxyPassMatch limits forwarding to URLs that contain a PHP filename, including an optional path-info suffix. The final path after the pipe is the site’s document root as seen by FPM. A mismatch between that path and DocumentRoot commonly produces a 404 or causes the wrong file to be executed.

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

TCP virtual host

If the pool listens on 127.0.0.1:9000, use the TCP form instead:

ProxyPassMatch ^/(.*.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/example/public/

Keep the Apache DocumentRoot and the FastCGI filesystem prefix synchronized. A TCP listener bound to loopback is not reachable from other hosts; that is normally preferable unless you deliberately operate a separate FPM server.

SetHandler form

Some Apache configurations prefer a handler attached to PHP files:

<FilesMatch .php$>
    SetHandler proxy:unix:/run/php/php-fpm.sock|fcgi://localhost/
</FilesMatch>

Handler syntax and path handling differ between Apache releases and layouts. Use the form documented for your installed version, and verify that the resulting script filename maps into the same document root. Do not enable both competing mappings in one virtual host unless you have a specific reason; overlapping rules make diagnosis harder.

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

Set document-root and directory access correctly

Apache must be able to traverse every parent directory and read the requested script. The virtual host’s <Directory> block should authorize only the intended site tree. If you use .htaccess, set AllowOverride to the minimum feature set your application needs instead of enabling every override.

Set DirectoryIndex index.php index.html when a directory request should resolve to PHP first. Keep application secrets, deployment files and database credentials outside the document root whenever possible. Explicitly deny access to files such as environment files, logs, SQL dumps and private configuration files if they can exist beneath the public tree.

Fix PHP-FPM socket ownership and permissions

Apache’s runtime user must be able to connect to a Unix socket. In the FPM pool, inspect and set the listener controls:

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

The correct user and group may be apache, httpd, www-data or a dedicated shared group, depending on the distribution and your Apache configuration. Use the actual account shown by Apache’s service definition. A shared group is appropriate when both services need access; add only the required members.

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

A mode of 0660 allows the owner and group to connect without making the socket world-writable. Avoid 0666 or broader permissions. After changing pool settings, restart or reload FPM so the socket is recreated with the new ownership and mode. If an upgrade leaves an old socket behind, stop FPM, remove only the stale socket after confirming no live service uses it, and start FPM again.

Validate, reload and test

  1. Check Apache syntax. Run sudo apachectl configtest. Proceed only when it reports Syntax OK.
  2. Reload Apache. Use sudo systemctl reload apache2 on Debian-style systems or sudo systemctl reload httpd on systems using the httpd unit.
  3. Create a temporary test script. In the document root, create health.php containing <?php echo "okn";. A script that prints a fixed string is safer than exposing a full diagnostic page.
  4. Request it locally. Run curl -i http://example.test/health.php, using the host name that selects your virtual host. A successful response has an HTTP status such as 200 and the body ok.
  5. Remove the test file. Delete health.php immediately after verification. Do not leave phpinfo() or debugging output publicly accessible.

If you need to inspect a failure, watch the Apache error log and the FPM service log while making one request. Paths vary, so journalctl -u php-fpm and journalctl -u apache2 or journalctl -u httpd are portable starting points.

Troubleshoot common failures

Why is Apache downloading my PHP file?

Apache is serving the script as a static file because the PHP handler did not match. Confirm that proxy and proxy_fcgi are loaded, that the virtual host containing ProxyPassMatch is the one selected for the request, and that the regular expression actually matches the URL. Check for a later rule that overrides the handler. Reload Apache after every configuration change.

Why do I get a 404?

Compare the virtual host’s DocumentRoot, the URL you requested and the filesystem prefix in the FastCGI mapping. The script must exist under that root, and the FPM backend path must point to the same location. Also verify that DirectoryIndex names the file you expect and that you are not testing a different virtual host because of an incorrect Host header.

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

Why do I get a 403?

Inspect directory traversal and read permissions from the filesystem root through the script. Then review Apache authorization directives, including Require all granted for the intended public directory and any deny rules that might match the filename. Mandatory access-control systems can also block Apache even when Unix permissions look correct; their denials will appear in the operating system’s security log.

Why am I getting a 502 Bad Gateway or 503?

These responses mean Apache could not obtain a valid response from FPM. Check that the FPM service is running, that Apache’s socket or TCP address exactly matches the pool’s listen value, and that the socket owner, group and mode permit Apache to connect. Read both service logs for connection-refused, permission-denied or crashed-worker messages. A stale socket after a PHP upgrade is another frequent cause.

Why do requests time out?

Timeouts can result from too few FPM workers, long-running PHP code, an undersized request timeout or unsuitable connection reuse. Inspect pool capacity, active and idle workers, Apache proxy settings and application logs together. Apache documentation warns that inappropriate FastCGI connection reuse can leave PHP-FPM workers busy and contribute to request timeouts; review reuse settings against the number of workers your pool can actually serve.

Why is the wrong PHP version running?

Check the FPM service and socket named by the virtual host rather than relying on php -v in a shell. If multiple pools exist, each can listen on a different versioned socket. Remove stale mappings and old sockets after a version migration, then reload Apache and test the selected pool again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Tune PHP-FPM without exhausting the server

FPM pools expose worker controls such as pm, pm.max_children, pm.start_servers, pm.min_spare_servers and pm.max_spare_servers. Choose limits from measured PHP worker memory usage and the memory left after Apache, the operating system and databases are accounted for. A higher worker count increases concurrency but can trigger swapping or out-of-memory kills.

Use a separate pool when applications need different users, PHP settings or capacity limits. Set pool-specific logs and monitor slow requests. Increase limits only after confirming that workers, CPU, memory and downstream services are the actual bottleneck; otherwise a larger queue merely moves the failure elsewhere.

Security and operational hardening

  • Run each sensitive application in a separate FPM pool with a least-privileged account.
  • Restrict socket ownership and mode to Apache and the intended pool group; never make a production socket world-writable.
  • Keep Apache, PHP, FPM and extensions patched through your distribution’s normal update process.
  • Store secrets outside the document root and deny access to environment files, logs, backups and database dumps.
  • Protect upload and temporary directories from unintended script execution when your application permits it.
  • Monitor Apache access/error logs and FPM logs, including worker exhaustion, slow requests and repeated backend failures.
  • Remove diagnostic scripts and temporary configuration after testing.

PHP-FPM versus mod_php

mod_php embeds PHP in Apache workers. PHP-FPM keeps PHP outside Apache and connects through FastCGI. The right choice depends on application age and the Apache process model you must support.

Decision area PHP-FPM with mod_proxy_fcgi mod_php
Process isolation PHP workers are separate from Apache and can be restarted independently. PHP runs inside Apache worker processes.
Per-pool users Separate pools can run as different Unix users for application isolation. Isolation is tied to Apache’s process user and module design.
Worker controls FPM pools expose dedicated worker counts, spare-worker policies and limits. Concurrency follows Apache’s worker model rather than independent PHP pools.
Apache MPM compatibility Works with modern threaded Apache MPMs because PHP is external. Historically constrained by the compatibility requirements of the embedded PHP module.
Restart independence FPM and Apache can be restarted separately, reducing the scope of some changes. Changing PHP generally requires restarting Apache workers.
Memory behavior Memory is concentrated in FPM workers and can be bounded per pool, although each worker still consumes resources. PHP memory is part of Apache worker processes, which can increase the cost of serving otherwise static traffic.
Operational complexity Requires a listener, socket permissions, proxy mapping and two services to monitor. Simpler for a documented legacy setup, but offers fewer pool and isolation controls.
Best fit The modern default for Apache deployments that need pool controls, multiple applications or threaded MPMs. Only a documented legacy combination that still depends on the embedded module.

For a new Apache deployment, PHP-FPM is usually the practical default. Retain mod_php only when a specific legacy application and its supported Apache/PHP combination require it, and document that constraint before migrating.

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

Pre-production checklist

  • Apache, PHP and FPM versions are supported by your distribution.
  • The active FPM pool’s listen value exactly matches Apache’s Unix-socket or TCP target.
  • The FastCGI filesystem prefix exactly matches DocumentRoot.
  • proxy and proxy_fcgi are loaded, and apachectl configtest passes.
  • Apache can traverse and read the application directory, while sensitive files are denied.
  • The socket is owned by the intended account or group with a restrictive mode.
  • A temporary script returned the expected response through the intended virtual host, and the script was deleted.
  • FPM worker limits fit available memory, and logs and alerts are monitored.

With those checks complete, Apache is handling HTTP and static content while PHP-FPM provides a controlled, independently managed FastCGI runtime for PHP requests.

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 *

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.