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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Configure Nginx to serve your site’s static files and pass requests ending in .php to a PHP-FPM pool over a Unix socket (preferred on a single VPS) or a protected loopback TCP listener. The two settings that must agree are Nginx’s fastcgi_pass value and the pool’s listen value; SCRIPT_FILENAME must resolve to the real PHP file below the server block’s document root. Install the packages, identify the active pool and service names for your distribution and PHP version, test the configuration, then verify it with a temporary script before putting the site into production.

How the Nginx–PHP-FPM connection works

Nginx is an HTTP server. It reads images, CSS, JavaScript and other static files directly from the document root. PHP-FPM (FastCGI Process Manager) is a separate service that keeps PHP worker processes ready to execute scripts. When a request matches a PHP location, Nginx packages the request as FastCGI parameters and sends it to the FPM pool. FPM runs the script and returns the generated response to Nginx, which sends that response to the client.

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

This separation means Nginx never executes a PHP file itself. A broken hand-off produces a gateway error even when Nginx is running normally. A wrong script path can instead produce a 404 or an FPM “primary script unknown” error. Treat the socket or TCP endpoint, the script filename and the filesystem permissions as three separate checks.

Before you change anything

Confirm the distribution, PHP version and service manager

Package names, unit names and socket filenames differ between Debian-based distributions, Red Hat–based distributions and PHP versions. Record what is installed instead of copying a path from an old tutorial.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
cat /etc/os-release
php -v
systemctl list-unit-files | grep -E 'nginx|php.*fpm'

If php -v is not available, PHP may not yet be installed. If several FPM units are listed, use the unit that corresponds to the PHP version serving this site.

Choose a document root and a dedicated server name

Decide where the site files will live, for example /var/www/example. The directory in Nginx’s root directive must be the same directory from which you expect PHP files to be executed. Create it and assign ownership according to your deployment model; do not make the entire tree world-writable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo install -d -m 0755 /var/www/example

On many Debian installations the web worker runs as www-data; on many Red Hat–based installations it runs as nginx. Check the active Nginx configuration or service account before choosing group ownership.

Install Nginx and PHP-FPM

Debian and Ubuntu

Install the distribution packages with APT. The generic package name is php-fpm; a repository may resolve it to a versioned package such as php8.3-fpm. Add php-cli when you need command-line diagnostics.

sudo apt update
sudo apt install nginx php-fpm php-cli

Enable and start Nginx. Enable the FPM unit that APT installed; the exact name can include the PHP major and minor version.

systemctl list-unit-files | grep 'php.*fpm'
sudo systemctl enable --now nginx
sudo systemctl enable --now php8.3-fpm   # replace with the unit shown on your VPS

RHEL, Rocky, AlmaLinux and Fedora

Use DNF and the repository’s PHP stream. The usual packages are php-fpm, php-cli and nginx, but a third-party repository may use versioned names.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo dnf install nginx php-fpm php-cli
sudo systemctl enable --now nginx
sudo systemctl enable --now php-fpm

Use systemctl status and journalctl -u with the unit name actually installed. Do not assume that a service called php-fpm exists on every system.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Find the active PHP-FPM pool and its listener

FPM reads one or more pool files. The common pool is named www, but applications can have separate pools. Locate the files and inspect the effective listen directive.

# Debian and Ubuntu
sudo grep -R "^[[:space:]]*listen[[:space:]]*=" /etc/php/*/fpm/pool.d/ 2>/dev/null

# RHEL-family distributions
sudo grep -R "^[[:space:]]*listen[[:space:]]*=" /etc/php-fpm.d/ 2>/dev/null

A pool can listen on a Unix-domain socket such as /run/php/php8.3-fpm.sock, on a port such as 127.0.0.1:9000, or on an IP address and port. Copy the value exactly, including the path, address and port. The value in Nginx’s fastcgi_pass must match it character for character.

To see which configuration a running service loaded, inspect its unit and recent log entries:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo systemctl status php8.3-fpm
sudo journalctl -u php8.3-fpm --since "15 minutes ago"

Replace the unit name with the one on your server. If you edit a pool file, reload or restart that matching FPM unit; changing Nginx alone does not make FPM reread its pool settings.

Configure a secure FPM pool

Unix socket: the normal choice for one VPS

A Unix socket stays on the host and avoids exposing a FastCGI port to the network. In the pool file, set a socket path and permissions that allow the Nginx worker to connect:

listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

Use the Nginx worker’s real user and group. On a Red Hat–family system those names are often nginx rather than www-data. A mode of 0660 gives the owner and group access without granting every local user access. The runtime directory may be recreated at boot, so configure ownership in the pool rather than fixing the socket manually after each restart.

Loopback TCP: useful for a deliberate topology

TCP can be appropriate when Nginx and FPM are separated into containers or hosts, or when your operational tooling requires a port. Bind it to loopback when both services are on the same VPS:

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.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1

In Nginx, use fastcgi_pass 127.0.0.1:9000;. Never bind FPM to a public interface unless you have a tightly controlled private network and an explicit security design. PHP’s documentation warns that an exposed FastCGI endpoint allows arbitrary code execution; an untrusted network must not be able to reach it.

Restrict executable extensions

Keep the pool’s security.limit_extensions limited to extensions your application really executes, normally .php and any explicitly required variant. This reduces the chance that a web-server mistake causes a non-PHP file to be sent to the interpreter.

Run the pool with least privilege

Pool directives such as user and group determine the account used by PHP workers. Give that account write access only to directories that must receive uploads, caches or generated files. Keep application code, configuration files and secrets non-writable by the worker whenever possible.

Create the Nginx server block

Create a site configuration in the location used by your distribution, such as /etc/nginx/sites-available/example with a link in sites-enabled, or a file under /etc/nginx/conf.d/. This representative block assumes a Unix socket; replace the root, server name and socket with your values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    listen [::]:80;
    server_name example.test;

    root /var/www/example;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

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

Why each PHP directive matters

  • location ~ .php$: matches requests whose path ends in .php. Keep the expression narrow; do not pass every request to FPM.
  • try_files $uri =404;: checks that the requested script exists below the configured root before sending it to PHP. A missing script therefore returns 404 instead of being interpreted.
  • include fastcgi_params;: supplies the standard FastCGI request variables. The distribution may provide fastcgi.conf instead; inspect the file before including both, because duplicate parameter definitions can be confusing.
  • fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;: builds the absolute filesystem path PHP uses as the script name. Nginx’s fastcgi_pass does not determine that path.
  • fastcgi_pass: points to the exact FPM listen value. For a socket use unix:/absolute/socket/path; for TCP use address:port.

For POST requests, FPM needs the request method, content type and content length. A current distribution’s fastcgi_params or fastcgi.conf should provide them. If your packaged include is unusually old or customized, verify that those parameters are present before debugging application forms.

Enable the site and protect the default configuration

On Debian and Ubuntu, link the file into sites-enabled and remove the default site only if you no longer need it:

sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/example
sudo nginx -t

On systems using /etc/nginx/conf.d/, placing a file there is normally sufficient. Do not remove a distribution file until you have confirmed which server block answers your hostname.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Apply changes safely

  1. Check the Nginx configuration before touching the running service: sudo nginx -t. Fix every reported file, line and include error.
  2. After a successful test, reload Nginx so existing connections are handled gracefully: sudo systemctl reload nginx.
  3. When a pool file changed, reload the matching FPM unit: sudo systemctl reload php8.3-fpm. If that unit does not support reload or fails to apply the change, use sudo systemctl restart php8.3-fpm.
  4. Check both services: sudo systemctl --no-pager --full status nginx php8.3-fpm.

A syntax test proves that Nginx can parse its configuration; it does not prove that the socket exists or that the worker can access it. Verification over HTTP is still required.

Verify PHP execution without exposing diagnostics

Create a short-lived file in the configured document root. The following command writes a script that emits only ok:

printf '%sn' '<?php echo "ok";' | sudo tee /var/www/example/health.php > /dev/null
curl -i http://example.test/health.php
sudo rm /var/www/example/health.php

A successful response should contain an HTTP success status and the body ok. Remove the file immediately; do not leave a diagnostic script on a public site. For HTTPS virtual hosts, request the real hostname with the correct TLS configuration instead of testing an unrelated default server.

When a test fails, inspect logs from both sides:

sudo tail -n 50 /var/log/nginx/error.log
sudo journalctl -u php8.3-fpm --since "10 minutes ago"

Pool-specific error and slow logs may be configured in the FPM pool file. Prefer these logs to displaying PHP errors or stack traces to visitors.

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

Diagnose common failures

502 Bad Gateway

  • Socket or port mismatch: Compare fastcgi_pass with the active pool’s listen line. A version change can leave Nginx pointing at an old filename.
  • FPM is stopped: Check systemctl status and the unit journal. Start or enable the correct versioned service.
  • Socket does not exist: Confirm the parent runtime directory and inspect the FPM startup log for a failure to create the socket.
  • Permission denied: Check socket owner, group and mode, then verify the Nginx worker account belongs to the configured group. Also check directory execute permissions on every parent directory.
  • TCP connection refused: Confirm that FPM is listening on the address and port you configured and that a local firewall rule is not blocking it.

404 from try_files

The requested path is not a file below the server block’s root, or the request reached a different server block. Confirm the hostname, root path, filename case and the active configuration with sudo nginx -T. Do not “fix” this by removing try_files; forwarding arbitrary paths to PHP can execute unintended files.

“Primary script unknown” or a blank PHP response

FPM received a script filename that does not exist from its point of view. Check that SCRIPT_FILENAME combines the correct root and $fastcgi_script_name, and that Nginx and FPM see the same filesystem when containers or mounts are involved. Confirm that the worker account can read the file and traverse its parent directories.

PHP source code downloads instead of executing

The request did not enter the PHP location, or Nginx is not connected to FPM. Check for a typo in the regular expression, server block selection and fastcgi_pass. Never serve source files as a workaround; stop and correct the routing.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Slow requests or timeouts

fastcgi_read_timeout controls how long Nginx waits between successive reads from FPM. Increase it only for operations that legitimately take longer, and investigate slow logs and application behavior first:

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.
location ~ .php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_read_timeout 120s;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}

A larger timeout does not create more PHP capacity; it can allow more requests to occupy workers while a backend is stalled.

Choose Unix sockets or TCP deliberately

Option Configuration Security and operational characteristics Use it when
Unix socket listen = /run/php/php-version-fpm.sock
fastcgi_pass unix:/run/php/php-version-fpm.sock;
Traffic remains local. Access is controlled by filesystem ownership and mode. The path must exist after boot and be readable by Nginx. Nginx and FPM run on the same VPS, which is the usual deployment.
Loopback TCP listen = 127.0.0.1:9000
fastcgi_pass 127.0.0.1:9000;
Easy to route through containers or separate processes, but it is still a network service. Bind locally and use listen.allowed_clients where appropriate. You need TCP for topology or tooling and can keep the listener off public interfaces.
Public TCP An address reachable from an untrusted network Unsafe for a normal VPS. An exposed FastCGI endpoint can permit arbitrary code execution. Not a safe default; avoid it unless a controlled private network and strict access controls are part of the design.

Tune FPM capacity without guessing

Process-management modes

Mode How workers are created Trade-off
dynamic Keeps a baseline of idle workers and grows toward pm.max_children as demand rises. Balances latency and memory for sites with variable traffic.
ondemand Starts workers when requests arrive and retires idle workers after the configured idle period. Can conserve memory on infrequently used sites, with process-start overhead during bursts.
static Maintains exactly pm.max_children workers. Predictable concurrency, but reserves the greatest amount of memory.

Set pm.max_children from measurements

pm.max_children is a concurrency ceiling, not a recommended universal number. Measure the resident memory of representative PHP workers under realistic traffic, reserve RAM for the operating system, Nginx, databases and caches, then choose a ceiling that does not trigger swapping. Watch FPM status metrics, system memory and response latency after each change. If the VPS has multiple pools, their combined ceilings matter.

Use FPM’s pool logging, slow logs and status features to find saturated workers and slow scripts. Raising the ceiling can increase throughput only when RAM and the downstream database can support the additional concurrency; otherwise it increases contention and failure risk.

Production hardening checklist

  • Use a local Unix socket unless your topology requires TCP.
  • Ensure the socket owner, group and mode permit the Nginx worker to connect but do not grant unnecessary access.
  • Keep FPM unreachable from untrusted networks; use loopback binding and firewall rules for TCP.
  • Keep security.limit_extensions restricted to extensions your application executes.
  • Run PHP workers with the least filesystem privilege and keep secrets outside web-accessible directories.
  • Serve the site over TLS and redirect clear-text HTTP after validating the certificate and virtual host.
  • Apply operating-system, Nginx and PHP security updates through your distribution’s supported channels.
  • Retain Nginx and FPM error logs, rotate them, and protect them from public download.
  • Keep try_files $uri =404; in the PHP location unless you have a documented routing reason not to.
  • Remove temporary test scripts as soon as verification succeeds.

A repeatable change procedure

For future PHP upgrades or migrations, repeat this sequence rather than editing a socket path blindly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Install the target PHP-FPM package and identify its unit name.
  2. Inspect the target pool’s listen, socket ownership and mode.
  3. Update fastcgi_pass to that exact listener and confirm SCRIPT_FILENAME still maps to the real document root.
  4. Run sudo nginx -t; stop if it fails.
  5. Reload Nginx, then reload or restart the matching FPM unit.
  6. Request a temporary ok script, inspect both logs, and delete the script.
  7. Only after the test succeeds, disable the old FPM unit and remove obsolete pool files.

The essential wiring is simple: Nginx’s PHP location must point to the listener declared by the active FPM pool, and the filename parameter must point to a real readable script. Keeping those values, permissions and service versions aligned prevents most configuration failures while preserving the security boundary between the web server and PHP workers.

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.