Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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 NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Fix Nginx Not Executing PHP on a Second Site

A second Nginx site usually fails to execute PHP because the request hits the wrong virtual host, the PHP location is missing, the script path is wrong, or fastcgi_pass does not match PHP-FPM. Follow this routing-first checklist to identify and fix each cause.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When PHP works on one Nginx virtual host but not another, the cause is usually routing or a site-specific FastCGI setting—not PHP itself. Verify that the request reaches the second server block, give that block the correct document root and PHP location, point fastcgi_pass at the PHP-FPM pool’s actual listener, and set SCRIPT_FILENAME from the second site’s root. Validate the active configuration with nginx -t and nginx -T, reload Nginx, then use the access and error logs to confirm the fix.

Why the first site works while the second site fails

Nginx does not execute PHP files itself. It selects a virtual host from the request’s destination address, port, and Host header, then applies that server block’s location rules. A PHP request is executed only when a matching location forwards it to PHP-FPM through FastCGI. The two sites can therefore use the same Nginx and PHP installation while behaving differently because one of these per-site relationships is wrong.

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 hostname does not match the second block’s server_name, so Nginx sends the request to the default server for that address and port.
  • The second site’s configuration file is not included in the running configuration, or an edit was made to a file Nginx is not using.
  • The second block has the wrong root, so the requested script path points into the first site or to a nonexistent file.
  • No PHP-matching location exists in the second block, or another location takes precedence.
  • fastcgi_pass points to a socket or TCP address different from the PHP-FPM pool’s listen value.
  • SCRIPT_FILENAME resolves to the wrong absolute path, producing “File not found” or “Primary script unknown.”

Diagnose in that order. It prevents you from changing PHP-FPM when the request is actually landing on the first site’s server block.

1. Prove that the request reaches the second virtual host

Inspect the configuration Nginx is actually running

Do not rely only on the file you recently edited. Dump the complete active configuration:

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
sudo nginx -T

Search the output for the second hostname and inspect every relevant server block. Confirm that the block has the intended listen address and port, the exact server_name, and the second site’s root. Also verify that the top-level configuration includes the file. A file sitting in a configuration directory has no effect if it is outside the active include chain.

To identify where this Nginx build expects its main configuration, run:

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

The output includes the compiled configuration path and helps you inspect the correct top-level file. On distributions that use a separate “available” and “enabled” directory, check that the second site’s enabled entry is present and not a broken link; the directory names and include paths vary by distribution.

Test the Host header without waiting for DNS

When DNS is being changed or a hostname is not yet pointing at the server, send the hostname explicitly to the local listener:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
curl -I -H 'Host: second.example' http://127.0.0.1/

The Host value must match a name in server_name. If it does not, Nginx routes the request to the default server for that listen address and port. Seeing the first site’s headers or content in this test is strong evidence of a server-name, port, or enabled-file problem rather than a PHP-FPM problem.

Check for subtle matching errors

  • Include both the bare name and the www name if users access both, for example server_name second.example www.second.example;.
  • Make sure the request uses the same port declared by the block. A block listening on port 80 does not handle an HTTPS request on port 443 unless a corresponding TLS server block exists.
  • Check spelling, punctuation, and trailing characters in the hostname. A near match is still a mismatch.
  • Look for another block using the same listen address and a default designation that catches unmatched hosts.

2. Give the second site a complete PHP-enabled server block

Adapt the following example to your hostname, directory, PHP version, and listener. The relationships between the directives matter more than the literal paths:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name second.example www.second.example;

    root /var/www/second.example/public;
    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;
    }
}

What each part does

  • listen and server_name determine which requests select this virtual host.
  • root defines the second site’s filesystem base. It must be the directory that actually contains the site’s public files.
  • index index.php index.html lets a directory request resolve to an index script before Nginx processes it.
  • The location / rule serves existing files and directories. The fallback shown is appropriate for applications that route requests through index.php; a purely static site may not need that fallback.
  • location ~ .php$ matches PHP URIs and sends them to FastCGI instead of returning PHP source as a downloadable or displayed file.
  • try_files $uri =404; prevents Nginx from forwarding a nonexistent script to PHP-FPM.
  • include fastcgi_params supplies the standard FastCGI request variables for the distribution’s Nginx setup.
  • fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; combines this server block’s root with the requested script URI.
  • fastcgi_pass names the PHP-FPM Unix socket or TCP endpoint that will execute the script.

How index.php reaches the PHP location

A request for the site’s directory can be internally redirected to /index.php by the index processing step. Nginx then evaluates location matching again, and the PHP regular-expression location handles the resulting URI. If the front controller is not reached, inspect the index directive, the try_files fallback, and any more-specific location that may intercept the request.

3. Match fastcgi_pass to the PHP-FPM pool listener

Read the pool’s listen value

PHP-FPM pool configuration contains a listen = directive. Read the pool used by the second site and copy that value exactly into Nginx:

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
  • For a Unix socket, a pool might listen on a path such as /run/php/php8.3-fpm.sock; Nginx must use fastcgi_pass unix:/run/php/php8.3-fpm.sock;.
  • For TCP, a pool might listen on an address and port; Nginx must use the same host and port, for example fastcgi_pass 127.0.0.1:9000; when that is the pool’s configured listener.

The PHP version in the socket name is not a universal constant. It differs by operating system, installed version, and pool configuration. Never infer it from the first site’s configuration; inspect the second site’s intended pool.

Check service state and socket access

A 502 response or “connection refused” generally means PHP-FPM is stopped, the listener path is wrong, or Nginx cannot open the socket. Confirm that the relevant PHP-FPM service is running, that the socket exists after startup, and that its ownership and permissions allow the Nginx worker to connect. If you use a Unix socket and changed the pool user or mode, re-check those permissions after every service restart.

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

PHP-FPM should not be exposed to an untrusted network. A TCP listener intended only for local Nginx should be bound to an appropriate local address and protected by the host firewall; do not make an internal FPM endpoint publicly reachable just to make the second site work.

Separate pools versus one shared pool

Arrangement Operational characteristics What Nginx must match
One shared PHP-FPM pool Less duplicated configuration and commonly one reusable PHP location include; sites share the pool’s process and limit settings. Each site’s fastcgi_pass points to the shared pool listener.
One pool per site Separate users, limits, and process controls improve isolation, but add pool configuration and permission work. Each server block must point to its own pool listener, which may be a different socket or TCP endpoint.

Choose based on isolation and operations, not on whether PHP can execute at all. Either arrangement works when the listener, permissions, and script path are correct.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

4. Make SCRIPT_FILENAME resolve to the second site’s real file

PHP-FPM receives a filesystem path, not merely a URL. The standard pattern in the example, $document_root$fastcgi_script_name, derives that path from the selected server block. For https://second.example/admin.php with a root of /var/www/second.example/public, it resolves to /var/www/second.example/public/admin.php.

Verify the path on disk

  1. Identify the exact root in the second server block.
  2. Check that the requested PHP file exists beneath that directory. For an index request, verify the actual index.php location.
  3. Check directory traversal permissions so the Nginx worker and PHP-FPM process can read the file.
  4. Ensure a copied configuration does not contain the first site’s hard-coded path in SCRIPT_FILENAME.

A stale value such as /var/www/first.example/public$fastcgi_script_name sends every second-site request to the wrong tree. That produces “File not found” or “Primary script unknown” even though the URL appears correct.

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.

Understand URI rewrites and front controllers

With a front-controller rule, the browser may request a route such as /profile/settings while Nginx internally passes /index.php to PHP-FPM. The script filename must describe the internally selected PHP script, not a guessed path based on the original route. Review rewrite and try_files behavior when only application routes fail while a direct request to a PHP file succeeds.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

5. Use the symptom to narrow the fault

Observed result Most likely cause First checks
PHP source downloads or appears as text No matching PHP location, or the request reached the wrong server block Run nginx -T; verify the second block contains location ~ .php$ and that the Host header selects it.
“File not found” or “Primary script unknown” Wrong root, stale copied SCRIPT_FILENAME, or a URI that does not map to a real file Confirm the file exists beneath the second root and use $document_root$fastcgi_script_name.
502 Bad Gateway or connection refused PHP-FPM is stopped, or fastcgi_pass does not match the pool listener Read the pool’s listen value, verify the socket or TCP endpoint, and check service status.
The first site’s page appears Hostname/server-name mismatch, wrong port, or second site file not included or enabled Use an explicit Host-header curl request and inspect nginx -T.
CSS, JavaScript, or front-controller routes fail A more-specific location or incorrect try_files rule intercepts the request Review location precedence, the fallback URI, and internal redirects.

Why PHP source is a high-priority warning

If a server sends PHP source, the request was not handed to PHP-FPM. Fix the Nginx routing and PHP location before exposing the site publicly; source disclosure can reveal credentials, database details, and application logic.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Why a 502 is different from a 404

A 404 from try_files can be an intentional result for a missing script. A 502 indicates that Nginx attempted FastCGI communication and failed, so focus on the FPM service, listener, socket path, and permissions rather than changing the document root first.

6. Validate, reload, and observe the running system

Check syntax before reloading

sudo nginx -t
sudo nginx -T > /tmp/nginx-active.txt
sudo systemctl reload nginx

nginx -t catches syntax and file-reference errors without replacing the running configuration. The configuration dump saved to /tmp/nginx-active.txt lets you search the exact effective server block, including inherited directives and included files. Reload only after the test succeeds.

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

Use logs from the affected server

Inspect the relevant access and error logs immediately after making a request. The access log confirms which URI and status code Nginx served. The error log commonly identifies an upstream connection failure, a missing script, a permission denial, or an unexpected internal redirect. If several virtual hosts share a log, add or inspect per-server error_log settings so messages can be attributed to the second site. Temporary debug logging can help isolate location selection, but return to normal logging after diagnosis.

Use a controlled PHP test file

In a controlled environment, place a small diagnostic file such as phpinfo.php in the second site’s document root and request it directly. This separates PHP execution from application routing. Remove the file as soon as testing ends: a public PHP information page discloses server, path, module, and environment details that should not remain exposed.

7. A repeatable repair checklist

  1. Run nginx -T and locate the second site’s active server block.
  2. Confirm its listen address and port match the request, and its server_name matches the exact Host value.
  3. Confirm the configuration file is included and enabled by the top-level Nginx configuration.
  4. Verify root points to the second site’s real public directory and that the requested PHP file exists there.
  5. Verify index index.php and the try_files behavior required by the application.
  6. Verify a PHP location matches .php, includes the FastCGI parameters, and sets SCRIPT_FILENAME from the selected root.
  7. Read the intended PHP-FPM pool’s listen value and make fastcgi_pass identical, including the Unix-socket or TCP form.
  8. Check PHP-FPM service state, socket existence, and socket permissions.
  9. Run sudo nginx -t, inspect the effective dump again if needed, and reload Nginx.
  10. Test with an explicit Host header, then inspect access and error logs for the same request.
  11. Delete any diagnostic PHP file after confirming execution.

When a shared include is safe—and when to keep site settings separate

A shared PHP location include can reduce duplicated directives across virtual hosts, provided every site uses the same assumptions about parameters and the same FPM listener. Keep the root and any site-specific routing in each server block. If pools differ, do not hide fastcgi_pass in a shared include unless the include mechanism reliably supplies the correct endpoint for each site.

Separate pools are preferable when sites need different Unix users, resource limits, or stronger process isolation. They also make mistakes more obvious: every server block must name its own socket, and every socket must have permissions compatible with Nginx. A shared pool is simpler to operate, but a failure or limit in that pool affects all sites using it.

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

What not to change first

  • Do not reinstall PHP merely because the second hostname fails; first prove which server block handled the request.
  • Do not copy the first site’s entire configuration and leave its root or hard-coded script path unchanged.
  • Do not guess a socket name from the installed PHP command-line version; the FPM pool’s listen directive is authoritative.
  • Do not expose a PHP-FPM TCP listener publicly to bypass a socket problem.
  • Do not leave phpinfo.php or verbose debug logging enabled after testing.

Final verification

The repair is complete when an explicit request for the second hostname selects the intended server block, static assets come from its document root, a direct PHP file executes through the intended FPM pool, front-controller routes reach the correct index.php, and the logs show no upstream or script-path errors. Those checks validate the running system rather than only the text of a configuration file.

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 *

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
PC Slower Than It Used to Be?Free scan - under a minute

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.