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 desk12 min

How to Fix Nginx and PHP Returning 404 Errors for Scripts

A practical, step-by-step guide to finding why Nginx returns 404 for PHP scripts, including root versus alias mapping, try_files, FastCGI settings, PHP-FPM filesystem paths and container-specific failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When Nginx returns 404 for a PHP script that appears to exist, the failure is usually a path-mapping problem. Nginx may be looking under the wrong root or alias, a try_files rule may reject the request, or PHP-FPM may receive a SCRIPT_FILENAME that does not exist in its filesystem. Trace the request from URI to Nginx location, resolved filename, and PHP-FPM endpoint; then fix the first mismatch you find.

First determine which component produced the 404

A browser’s “404 Not Found” page does not identify the failing component. Nginx can generate a 404 before PHP-FPM is contacted, or it can pass the request upstream and receive an error because PHP-FPM cannot open the script. The remedy differs, so start by recording evidence rather than changing directives at random.

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.
  • Record the exact URL, including path, query string, and the Host name used by the client.
  • Inspect the response with curl -i so you can see the status, Server header, redirects, and response body.
  • Capture the matching access-log and error-log lines at the same time. The usual files are under /var/log/nginx/, but the active configuration may specify another location.
  • From the shell, test whether the expected PHP file exists at the absolute path implied by the active configuration. Check filename case, symlinks, release-directory links, and URI prefixes.
curl -i -H 'Host: example.test' 'http://127.0.0.1/account/login.php?next=%2F'

sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log

# Substitute the path your configuration should resolve to
stat /var/www/example/public/account/login.php

Nginx’s Beginner’s Guide states that when the requested file does not exist, Nginx sends a response indicating a 404 error and recommends checking access.log and error.log when behavior is unexpected. A 404 with no FastCGI activity generally points to Nginx’s URI-to-file mapping; a request that reaches PHP-FPM requires checking the script path visible to that service.

See the configuration Nginx is actually running

Editing an included file is not enough if another server block wins the request or a later include overrides a parameter. Dump the complete, expanded configuration and identify the block selected for the request.

#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.
  1. Run sudo nginx -T with the same configuration and privilege context used by the service. Save the output while troubleshooting.
  2. Find the server block whose listen, server_name, and default-server status match the request’s address and Host header.
  3. Within that block and its inherited contexts, record root or alias, index, the PHP regular-expression location, try_files, include fastcgi_params, fastcgi_pass, and every fastcgi_param SCRIPT_FILENAME.
  4. Check for another regular-expression or more-specific prefix location that captures the URI before the PHP location you expected. Nginx location selection, not file order alone, determines which directives apply.

Validate syntax before any reload:

sudo nginx -t
sudo systemctl reload nginx

If validation fails, do not reload. Correct the reported file and line, run nginx -t again, and only then retest with a fresh request and fresh log lines.

Map the URI to a real file with root or alias

The active root or alias establishes the filesystem base. Nginx combines that base with the request URI (according to the directive’s mapping rules) when it checks a file. A visually correct URL can therefore point to a different directory than the one you inspected.

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

Document root mapping

With a document root such as root /var/www/example/public;, a request for /account/login.php is normally checked under /var/www/example/public/account/login.php. Verify that exact path, not a similarly named file in the project directory or an old deployment release.

server {
    root /var/www/example/public;
    index index.php;

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

Common root-related causes include a symlink that still points to an older release, a web root one directory above or below the application’s public directory, and case differences on a case-sensitive filesystem. A request for /Login.php does not necessarily match login.php.

Alias mapping

alias replaces the matching location prefix with a filesystem path. It is useful for mounting a directory at a URL prefix, but a mismatch between the location’s trailing slash and the alias path can produce an unexpected filename. Confirm the complete mapping for the exact URI and test a file inside the aliased directory before involving PHP.

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.
location /assets/ {
    alias /srv/site-assets/;
}

Do not assume that $document_root describes an aliased location. In a PHP location nested under or adjacent to an alias, construct SCRIPT_FILENAME from the mapping that actually serves the script, or use a tested explicit path. The goal is that the path sent to PHP-FPM names the same file Nginx would serve from that request.

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

Check filesystem access and deployment links

  • Use namei -l /var/www/example/public/account/login.php to inspect every parent directory and permission.
  • Use readlink -f on release symlinks to see the physical directory currently targeted.
  • Compare the path in the request with the application’s public URL prefix. If the site is mounted at /app/, decide whether the filesystem contains an app directory or whether the prefix is removed by a location mapping.
  • Check that a deployment did not delete the file while Nginx retained an old configuration or cache. Reload after a verified deployment change.

Understand what try_files is doing

try_files checks candidate files or directories in the current mapping. If none exists, its final argument can perform an internal redirect, return a status such as =404, or send the request to a named location. This directive is often where an apparently existing script is rejected.

Front-controller fallback

A typical application routes non-file URLs to a front controller:

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

Here, a missing path is intentionally rewritten to /index.php. That is appropriate for routes handled by the application, but it can hide a typo in a direct script URL. Confirm that the fallback is intentional for the URI you are testing and that the fallback script itself exists under the active root.

Reject missing PHP scripts before forwarding

Inside the PHP location, try_files $fastcgi_script_name =404; checks the script path derived from the request and stops a nonexistent script before PHP-FPM is contacted. A production configuration example uses this early check together with fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name. Add it only after you have verified the root or alias mapping; otherwise it will consistently reject a valid file because the mapping is wrong.

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

Do not confuse try_files with PHP execution. It only determines whether Nginx’s candidate path exists and whether to continue, redirect, or return a status.

Make the PHP location and FastCGI parameters agree

The PHP location must forward the request to the correct PHP-FPM socket, TCP host, or port, and it must identify the script using an absolute path that PHP-FPM can see. Nginx documents that “The SCRIPT_FILENAME parameter is used in PHP for determining the script name, and the QUERY_STRING parameter is used to pass request parameters.” A wrong script filename commonly appears as “Primary script unknown” or “No input file specified.”

Use a complete baseline configuration

server {
    root /var/www/example/public;
    index index.php;

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

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

This is a pattern to adapt, not a universal drop-in. The socket filename varies by distribution, PHP version, pool configuration, and packaging. A TCP endpoint may instead look like 127.0.0.1:9000. Use the endpoint configured by the active PHP-FPM pool.

Verify fastcgi_pass separately

A wrong or stopped endpoint usually produces a 502 Bad Gateway rather than a 404, but it must still be ruled out when logs contain mixed errors. Confirm that the socket exists and that its owner and mode permit Nginx to connect, or verify that the configured host and port are listening.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo ss -lx | grep php
sudo ss -ltnp | grep 9000
sudo systemctl status php-fpm

Use the service name present on your operating system if it differs. Do not “fix” a 404 by pointing at an arbitrary socket; select the pool that serves this application and confirm its process has access to the application files.

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.

Check SCRIPT_FILENAME from both processes’ viewpoints

$document_root$fastcgi_script_name works when Nginx’s document root is the same absolute path PHP-FPM uses. It fails in split deployments where Nginx sees /var/www/example/public but PHP-FPM sees the application mounted at /srv/app/public. In that case, either mount the application at the same path in both environments or set SCRIPT_FILENAME to the path PHP-FPM can actually open.

Never use a relative filename, a path that exists only on the host, or a path from a build stage that is absent from the runtime container. Compare mounts and permissions inside each container or host, then test the exact resulting path with stat there.

Preserve the query string and request method

Include the distribution’s FastCGI parameter file, then ensure QUERY_STRING is passed as required by the application. A missing query string does not normally create a file 404, but it can make a front controller appear broken after the path issue is fixed. Keep the parameter definitions consistent with the PHP-FPM package you installed.

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

Handle slash-ending requests and index files

A request ending in / does not name a PHP file by itself. If Nginx serves an index, the index directive and the PHP handoff determine which script is selected. In FastCGI processing, fastcgi_index index.php appends index.php to a URI ending in / when constructing $fastcgi_script_name.

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

Confirm that the directory requested by the client really contains the configured index file and that your try_files rule does not redirect the slash request somewhere else. Test both forms explicitly:

curl -i -H 'Host: example.test' http://127.0.0.1/admin/
curl -i -H 'Host: example.test' http://127.0.0.1/admin/index.php

If the direct file works but the slash URL fails, focus on index selection and the internal redirect rather than PHP-FPM connectivity.

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

A safe, repeatable troubleshooting procedure

  1. Freeze the failing request. Write down the exact URL, host, HTTP method, status, and timestamp. Use curl -i against the same virtual host so you do not accidentally test a default server.
  2. Identify the selected server and location. Run sudo nginx -T. Match the listen address, server_name, and location rules to the request.
  3. Resolve the expected path manually. Apply the active root or alias to the URI, account for prefixes and rewrites, and run stat on the resulting absolute filename. Correct case, symlinks, release links, and permissions before changing FastCGI settings.
  4. Inspect try_files. Determine whether it checks the URI, a directory, or $fastcgi_script_name; note whether its final action is an internal redirect or =404. Verify that a front-controller fallback is deliberate.
  5. Check the PHP location. Confirm the regular expression matches the request, the FastCGI include is present, and there is only one effective SCRIPT_FILENAME for this location. Later parameters can override earlier includes, so read the expanded configuration.
  6. Verify the endpoint. Confirm the configured socket or TCP listener exists, belongs to the intended PHP-FPM pool, and is reachable by Nginx. Treat a 502 or connection-refused message as a separate endpoint problem.
  7. Compare runtime filesystems. In containers or separate hosts, run stat for the computed script path inside both Nginx and PHP-FPM environments. Align mounts or change the parameter to the PHP-FPM-visible path.
  8. Validate and reload. Run nginx -t; reload only on success. Repeat the original curl -i request and inspect only the new log entries.
  9. Remove diagnostics. If you created an info.php-style file, protect it during the test and delete it immediately afterward. Do not leave a script that exposes runtime details on a public server.

Match symptoms to likely causes

Observed result Most likely location of the fault What to verify next
404 immediately, with no FastCGI log activity Nginx selected the wrong server/location, failed try_files, or mapped the URI to a nonexistent file Run nginx -T; trace root/alias, location selection, and the final try_files action
“Primary script unknown” or “No input file specified” from PHP SCRIPT_FILENAME names a path PHP-FPM cannot open Compare the computed absolute path with the PHP-FPM container or host; check mounts, case, and permissions
404 only for URLs with a directory prefix Alias or prefix mapping removes or duplicates part of the URI Test a known file in that prefix and inspect trailing slashes on the location and alias
Direct .php URL works, but a slash URL fails Index selection or fastcgi_index is inconsistent Confirm index index.php, fastcgi_index index.php, and the directory’s actual index file
Most unknown paths show the application homepage Front-controller fallback is working, possibly masking a mistyped script URL Decide whether the fallback is intended; test the real script path and review application routing
502 instead of 404 after a configuration change Nginx reached the PHP location but cannot connect to the configured FPM endpoint Check socket/port existence, pool status, listener address, and Nginx permissions

Container and multi-host deployments need path alignment

In a single host, $document_root$fastcgi_script_name often points to a file both services can see. In containers, Nginx and PHP-FPM may have different mount points even though they serve the same application. For example, Nginx may resolve /var/www/example/public/index.php while PHP-FPM has only /app/public/index.php. PHP then reports an unknown script, despite the file being present from Nginx’s perspective.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Compare the volume mounts and working directories in both service definitions.
  • Choose one shared absolute mount path when possible; it reduces ambiguity in logs and parameters.
  • If paths must differ, set SCRIPT_FILENAME to the PHP-FPM path and keep Nginx’s existence check consistent with the path it can test.
  • After changing mounts, restart the affected service and repeat stat and curl tests from clean containers.

A successful Nginx-side try_files check proves only that Nginx can see a file. It does not prove that PHP-FPM can open the same absolute name.

Use logs to prove the final fix

Once the path and endpoint are corrected, make one controlled request and correlate its timestamp with the access and error logs. The status should be stable across repeated requests, the expected PHP-FPM pool should receive the request, and unrelated URIs should retain their intended fallback behavior. Keep a known-good static file in the same document root to distinguish general virtual-host failures from PHP-specific mapping errors.

Do not disable access checks, broaden permissions indiscriminately, or remove try_files merely to make an error disappear. A configuration that forwards arbitrary nonexistent paths to PHP can obscure typos and increase the amount of untrusted input reaching the interpreter. Fail early with a verified path check, then address the underlying mapping or mount mismatch.

Decision checklist before you declare the issue solved

  • The request is handled by the intended server block and PHP location.
  • The URI maps to the expected file under the active root or alias.
  • The file exists with matching case, and every parent directory is traversable by the relevant service.
  • try_files performs the intended check or fallback, with no accidental rewrite masking a typo.
  • SCRIPT_FILENAME names a path visible to PHP-FPM, not merely to Nginx.
  • fastcgi_pass points to the active pool’s real socket or listener.
  • Slash-ending URLs select the intended index script.
  • nginx -t succeeds before reload, and a fresh curl -i request matches the expected logs.
  • Temporary diagnostic scripts have been removed and configuration changes are documented for the next deployment.

The reliable fix is the first point where the request’s URI, Nginx’s filesystem mapping, and PHP-FPM’s visible script path all agree. Once those three views match, a PHP 404 stops being a mystery and becomes a normal, observable configuration error.

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 *

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.