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
World desk10 min

How to Fix Nginx Not Executing PHP on a Second Site

When PHP works on one Nginx site but not another, verify virtual-host selection, the second site’s root, PHP location, SCRIPT_FILENAME, and the PHP-FPM listener in that order.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If PHP works on one Nginx site but the second domain shows the first site, downloads PHP source, returns “File not found,” or produces a 502 error, the cause is usually configuration routing rather than PHP code. Nginx must select the second virtual host, map its document root, match .php requests, and send them to the PHP-FPM listener that actually serves that site. Check those four relationships in order, then validate the active configuration and logs.

What must be correct for a second site to run PHP

Nginx does not execute PHP itself. It receives the HTTP request, chooses a server block, maps the URI to a file under that block’s root, and forwards PHP requests to PHP-FPM through FastCGI. A working first site proves only that one virtual-host path is correct; it does not configure the second site.

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.

For the second domain, verify these relationships:

  • The request’s host name and port select the intended server block.
  • The block is loaded by the running Nginx configuration and has the second site’s actual document root.
  • A PHP location such as location ~ .php$ catches the request and supplies FastCGI parameters.
  • fastcgi_param SCRIPT_FILENAME resolves to the real PHP file in the second root.
  • fastcgi_pass exactly matches the PHP-FPM pool’s listen = value.

A mistake in any one of these can look like “PHP is broken,” even when PHP-FPM and the first site are healthy.

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 edited. Display every included server block and directive with:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
sudo nginx -T

Search the output for the second domain, its listen directive, its server_name, and its root. If you need to determine which top-level configuration file and compile-time paths Nginx uses, run:

nginx -V

The second-site file must be included by the active configuration. On distributions that use an enabled-sites directory, a file sitting only in an available-sites directory is not active until it is enabled through the distribution’s normal include or symlink arrangement. The authoritative test is whether the block appears in nginx -T, not whether the file exists on disk.

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

Check the host and port match

Nginx chooses among server blocks using the local address, port, and request Host header. If no server_name matches for that address and port, Nginx sends the request to the default server. That is why a typo, an old DNS record, a missing www name, or a request sent to the wrong port can display the first site.

When DNS is still changing, test the second block directly against the local Nginx listener:

curl -I -H 'Host: second.example' http://127.0.0.1/

Replace second.example with the exact name in the second block. If this returns the second site while the public hostname does not, the virtual-host configuration is probably correct and the remaining issue is DNS, an upstream proxy, HTTPS termination, or the public request using a different port. If the explicit Host test still returns the first site, inspect server_name, listen, enabled-file inclusion, and default-server ordering.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Include every hostname you intend to serve

A block for second.example does not automatically match www.second.example. Add each required name explicitly, or use a deliberately chosen alias pattern. Also check whether the request is HTTPS: an HTTP block listening on port 80 cannot handle a request that arrives at a separate TLS server block on port 443.

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.

2. Give the second site a complete server block

Start with a self-contained block and adapt the hostname, paths, PHP version, and socket to your machine:

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;
    }
}

This example assumes the application’s public files are in /var/www/second.example/public and that PHP-FPM listens on the shown Unix socket. Those values are examples, not universal defaults. The important links are the block’s root, the PHP-matching location, the script filename expression, and an existing FastCGI endpoint.

Why the index and try_files directives matter

When a browser requests /, the index directive can select index.php. Nginx then internally redirects that request into the PHP location, where FastCGI processing occurs. For front-controller applications, try_files $uri $uri/ /index.php?$query_string; serves real files and directories directly and sends application routes to index.php while preserving the query string.

The try_files $uri =404; line inside the PHP location prevents Nginx from sending a nonexistent script to PHP-FPM. It also makes a wrong root or wrong URI visible as a 404 instead of an opaque FastCGI error. If your application intentionally generates virtual PHP paths, adjust this rule only with a clear understanding of that application’s routing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Check location precedence when static files or routes fail

Nginx evaluates location rules by its matching algorithm, not simply by the order in which they appear. A more specific prefix or regular-expression location can intercept a request before the PHP block does. If CSS, JavaScript, image files, or front-controller routes fail while a direct PHP file works, inspect all locations in nginx -T. Look for a nested or regular-expression rule that rewrites the URI, returns early, or points at another root.

3. Make SCRIPT_FILENAME point to the second site’s file

PHP-FPM needs the filesystem path of the script, not merely the URL. The standard pattern is:

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

For a request to /admin/test.php with a document root of /var/www/second.example/public, Nginx constructs a path equivalent to /var/www/second.example/public/admin/test.php. Confirm that the file really exists below that root and that the Nginx worker can traverse each parent directory and read the script.

Recognize stale copied paths

A common second-site mistake is copying the first site’s block and leaving a hard-coded value such as /var/www/first.example$fastcgi_script_name in SCRIPT_FILENAME. The browser may reach the correct virtual host, but PHP-FPM then receives a path belonging to the first site or to a file that does not exist. Replace the stale path with the second site’s root or use the document-root expression shown above.

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

Distinguish a missing file from a missing handler

If PHP source code is downloaded or displayed, Nginx did not pass that request to a PHP location. Check the server block selected by the Host header and verify that location ~ .php$ is present in the active configuration. If the response says File not found or Primary script unknown, the request usually reached PHP-FPM but the resulting script path is wrong, the file is outside the configured root, or the URI does not map to a real script.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

4. Match fastcgi_pass to the PHP-FPM pool

The value after fastcgi_pass must be identical to the PHP-FPM pool’s listen = setting. PHP-FPM may expose a Unix-domain socket or a TCP listener, and the path or port can differ by operating system, package, PHP version, and pool.

Unix socket example

If the pool configuration contains:

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

the Nginx directive must be:

fastcgi_pass unix:/run/php/php8.3-fpm.sock;

The unix: prefix is required for a socket path. Check that the socket exists after PHP-FPM starts and that its owner, group, and mode allow the Nginx worker to connect.

TCP listener example

If the pool instead contains:

listen = 127.0.0.1:9073

use:

fastcgi_pass 127.0.0.1:9073;

Do not substitute a different port merely because another site uses it. PHP-FPM must actually be listening at the address Nginx calls. A TCP listener should normally be bound to a trusted local address; the PHP manual warns against exposing FPM to an untrusted network.

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

Find the pool’s real listener

Read the pool configuration used by the installed PHP-FPM service and locate its listen = line. Package layouts vary, so use the service’s configuration paths rather than assuming that one versioned filename exists. Then check the service status and the operating system’s listening sockets. A running service with a different socket name is still the wrong endpoint for this server block.

When separate sites use separate pools, each block can point to its own socket or port. Keep the mapping deliberate: sending the second site to the first site’s pool can create unexpected Unix-user permissions, resource limits, or application-level isolation.

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

5. Diagnose the symptom instead of changing random directives

Observed result Most likely cause What to check
PHP source downloads or appears as text No PHP location matched, or the request went to the wrong server block Inspect nginx -T; verify the second block contains location ~ .php$ and that the Host name selects it.
File not found or Primary script unknown Wrong root, stale hard-coded SCRIPT_FILENAME, or a URI that does not map to a real file Confirm the script exists below the second root and use $document_root$fastcgi_script_name.
502 Bad Gateway or connection refused PHP-FPM is stopped, its socket is absent, permissions block access, or fastcgi_pass does not match listen = Check the pool listener, service status, socket ownership and mode, and the Nginx error log.
The first site appears Host or port mismatch, missing server_name, or the second file is not included/enabled Use an explicit Host-header curl request and confirm the block appears in nginx -T.
CSS, JavaScript, or application routes fail A more specific location, rewrite, or incorrect try_files rule intercepted the request Review all location rules, internal redirects, and the second site’s root.

Read both access and error logs

The access log shows which URI and status Nginx recorded; the error log usually explains an upstream connection failure, missing script, permission problem, or rewrite issue. If sites share global logs, add a temporary per-server error_log directive or otherwise identify requests by host. Debug-level logging can help isolate virtual-host and location selection, but enable it only for controlled diagnosis because it is verbose.

6. Validate, reload, and test safely

  1. Edit the second site’s active configuration. Confirm the hostname, port, root, PHP location, script filename, and FPM endpoint are internally consistent.
  2. Validate syntax and referenced directives before reloading:
    sudo nginx -t

    A successful test means Nginx accepted the configuration syntax; it does not prove that the correct virtual host or PHP socket will be selected.

  3. Save the complete running configuration for inspection when needed:
    sudo nginx -T > /tmp/nginx-active.txt

    Search this output for duplicate server names, an unexpected default server, an old root, or a second PHP location inherited from an include.

  4. Reload Nginx without dropping existing connections:
    sudo systemctl reload nginx

    If the reload fails, return to the error output from nginx -t; do not assume the edited file is active.

  5. Request the second hostname, then test a known PHP file beneath its root. Repeat the explicit Host-header test against 127.0.0.1 if public DNS or a proxy could obscure which block answered.
  6. For a controlled diagnosis, create a temporary file such as phpinfo.php in the second site’s document root, request it once, inspect the PHP-FPM and server details, and remove it immediately afterward. A public diagnostic page exposes configuration and environment information.
  7. Check the relevant access and error logs while making one request. The timestamp, host, URI, status, and upstream message together are more useful than repeatedly editing directives without observing the request.

7. Choose shared or separate PHP-FPM pools deliberately

There is no requirement that every site use a separate pool, but the choice affects permissions, limits, and maintenance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Arrangement Advantages Costs and checks
One shared pool Fewer pool files, fewer sockets, and a reusable PHP location include Sites may share the same Unix user, process limits, and failure domain; every block still needs the correct root and a working common listener.
One pool per site Separate Unix users, resource limits, sockets, and process isolation More configuration and monitoring; each site’s fastcgi_pass must point to its own pool listener, and socket permissions must allow only the intended Nginx access.

A shared include can reduce copy-and-paste errors in the PHP location, but do not hide a site-specific listener requirement inside a generic include. If the second pool uses another PHP version or socket, make that difference explicit in the second server block.

8. A repeatable recovery checklist

  • Confirm the requested hostname, scheme, and port.
  • Run nginx -T and verify that the second server block is loaded.
  • Check every intended name in server_name, including www if required.
  • Verify the block’s root is the second site’s real public directory.
  • Ensure index.php is listed where the application expects it.
  • Confirm the PHP regular-expression location is active and not overridden by another location rule.
  • Use try_files $uri =404; for direct PHP scripts unless the application has a documented alternative.
  • Use $document_root$fastcgi_script_name or another deliberately verified path for SCRIPT_FILENAME.
  • Read the PHP-FPM pool’s exact listen = value and copy it exactly into fastcgi_pass.
  • Check that PHP-FPM is running and that a Unix socket exists with usable permissions.
  • Run sudo nginx -t, inspect sudo nginx -T, and reload Nginx.
  • Observe access and error logs during a request, then remove any temporary diagnostic file.

When the configuration is correct but PHP still fails

If the explicit Host-header request selects the right block, the PHP file exists under the right root, and the listener matches the pool, focus on operating-system permissions and application behavior. Nginx needs directory execute permission to traverse the path and read permission for static and PHP files; PHP-FPM also needs access under the user configured for its pool. A 403 or a permission-denied message points to filesystem ownership or mode rather than virtual-host selection.

If only rewritten application routes fail, compare a direct request to an existing script with a request such as /account/profile. A working direct script confirms FastCGI connectivity; a failing route then points to the front-controller try_files rule, rewrite configuration, or application base URL. Conversely, if direct PHP requests fail with 502, investigate PHP-FPM and its socket before changing rewrite rules.

Finally, remember that a successful nginx -t checks syntax, not intent. Duplicate server blocks, an unexpected default server, an include loaded after your edit, or a second Nginx instance can leave the running behavior different from the file you believe you changed. Always compare the observed Host, active configuration dump, logs, and listener state as one chain.

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

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 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
Crashes, No Sound, or Screen Glitches?Free driver 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.