Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon 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 Now×
Skip to content
VGSources
Blog

How to Fix Nginx and PHP Returning 404 Errors for Scripts

A practical guide to finding whether NGINX or PHP-FPM generated a 404, then correcting root/alias mapping, try_files, SCRIPT_FILENAME, FastCGI endpoints, and container paths.
Length12 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A PHP 404 can come from two different places: NGINX may fail to map the URL to a file, or NGINX may forward a request that PHP-FPM cannot find in its own filesystem. Identify which process generated the response first, then make the URI, root/alias, try_files, and SCRIPT_FILENAME agree on one absolute path.

The reliable workflow is to inspect the active configuration, reproduce the exact request with curl, compare it with the real file on disk, verify PHP-FPM’s endpoint and filesystem view, and reload only after syntax validation.

As an Amazon Associate I earn from qualifying purchases.

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

What a 404 means in an NGINX/PHP stack

HTTP status 404 only says that the requested resource was not found. It does not identify the process that decided it was missing. NGINX can return the 404 before PHP runs, or PHP-FPM can receive the request and fail when it looks up the script named by SCRIPT_FILENAME.

NGINX generated the 404

NGINX builds a filesystem path from the request URI and the applicable root or alias. A try_files directive can then test files or directories, internally redirect to a fallback, or terminate with =404. If the resulting path does not exist, NGINX sends a 404 response. Its Beginner’s Guide recommends checking both access.log and error.log when behavior is unexpected.

#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.

PHP-FPM generated the 404-style failure

If the PHP location forwards a request but SCRIPT_FILENAME names a path that PHP-FPM cannot see, the upstream may report “No input file specified” or “Primary script unknown.” This is still a path-mapping problem, not proof that the URL itself is wrong.

Collect evidence before changing configuration

Do not begin by replacing directives at random. Capture one failing request and the exact configuration that handled it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Record the request. Write down the complete URL, HTTP method, query string, and Host header. A request can select a different virtual server when the host name is wrong.
  2. Reproduce it without a browser. Run curl -i -H 'Host: example.test' http://127.0.0.1/path/to/script.php?x=1. Save the status line, response headers, and body. A response generated by an application often looks different from NGINX’s default 404 page.
  3. Print the active configuration. With appropriate privileges, run nginx -T. Find the selected server block, its root or alias, the PHP location, try_files, fastcgi_pass, and every SCRIPT_FILENAME assignment. Included files and later overrides matter, so do not rely on the file you expected to be loaded.
  4. Read fresh logs. Match the request time and URI in NGINX’s access and error logs. Look for the selected host, an internal redirect, permission or path errors, and upstream messages. Clear timing makes it easier to distinguish the current request from an older failure.
  5. Check the file using the mapped absolute path. From the shell, run a command such as ls -l /var/www/example/public/path/to/script.php, using the path that the active configuration should construct. Check spelling, capitalization, symlinks, release-directory links, and the URI prefix.

How NGINX maps a URI to a PHP file

root appends the URI

With root /var/www/example/public;, a request for /play.php normally maps to /var/www/example/public/play.php. A request for /admin/play.php maps to /var/www/example/public/admin/play.php. The same base must be used when checking the file from the shell and when constructing the FastCGI script name.

alias replaces the location prefix

alias has different path semantics: the matching location prefix is replaced by the alias value. For example, a location such as location /assets/ { alias /srv/game-assets/; } maps /assets/menu.css to /srv/game-assets/menu.css. A PHP location placed under an aliased prefix can therefore produce a different path from one calculated with a document-root assumption. Verify the complete resulting path rather than substituting root for alias mentally.

Configuration base Request URI Expected file path What to verify
root /var/www/example/public; /index.php /var/www/example/public/index.php The file exists with the exact case.
root /var/www/example/public; /games/start.php /var/www/example/public/games/start.php The URI prefix was not accidentally duplicated.
alias /srv/game-assets/; in /assets/ /assets/icon.php /srv/game-assets/icon.php The alias replacement and trailing slashes match.

Build a correct PHP location

NGINX’s FastCGI module requires an endpoint and parameters describing the request. The endpoint is selected by fastcgi_pass; the script path is supplied by SCRIPT_FILENAME. NGINX documents the common document-root form $document_root$fastcgi_script_name, while also showing an explicit absolute path when the PHP directory is known.

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 copy-and-paste file. The document root, socket name, and PHP-FPM deployment differ by distribution and installation.

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.

Use try_files as a deliberate boundary

In the PHP location, try_files $fastcgi_script_name =404; checks the script path before forwarding it. Once the path mapping is proven, this makes NGINX reject a nonexistent script clearly instead of sending it upstream and producing an ambiguous PHP-FPM message. It also prevents a typo in a PHP URL from being treated as an application request.

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

Do not add this check blindly while the root or alias is still wrong. It will faithfully return 404 for every script if the candidate path is constructed in the wrong directory.

Make SCRIPT_FILENAME match PHP-FPM’s view

NGINX’s documentation states 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.” With a normal shared document root, $document_root$fastcgi_script_name is usually appropriate. If PHP-FPM runs in another container, chroot, or host, that absolute path may exist only in NGINX’s environment. In that case, configure a path that is valid from PHP-FPM’s filesystem view, or mount the application at the same path in both environments.

Handle directory requests and indexes

Requests ending in / need special attention. fastcgi_index index.php; appends index.php when NGINX constructs $fastcgi_script_name for such a URI. Also check the server’s index directive and the location that handles the directory request. A missing or differently named index file can look like a PHP 404 even though a neighboring script works.

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

Common causes and the precise correction

Symptom Likely cause Correction
Static files and PHP both return 404 The selected server block has the wrong root, or the request is reaching a different host block. Use nginx -T, confirm the Host header, and test a known-good static file under the active root.
Static files work; PHP says “No input file specified” SCRIPT_FILENAME points to a path PHP-FPM cannot see. Compare the absolute path in NGINX with the same path inside the PHP-FPM environment; align mounts or set the correct PHP-visible path.
Only URLs under a prefix fail An alias or URI prefix is being combined with a document-root formula incorrectly. Resolve the prefix replacement manually, verify the file, and use a script filename calculation that matches the alias layout.
Existing scripts return NGINX 404 after adding try_files The check is evaluating the wrong candidate path. Temporarily inspect the active root/alias and $fastcgi_script_name mapping; correct the base path before retaining the check.
Some names work, others fail Case differences, a missing symlink, or a release-directory link points elsewhere. Use ls -l on the exact path, resolve symlinks, and compare URL case with the on-disk filename.
The error changes to 502 The request now reaches an unavailable or incorrect PHP-FPM endpoint. Confirm the socket or TCP address named by fastcgi_pass exists and belongs to the active PHP-FPM pool.
A typo appears to load the application front controller try_files in the general location internally redirects every miss to /index.php?$query_string. Decide whether that fallback is intentional. Keep it for application routing, but do not use it to hide a malformed PHP script URL.

Check the PHP-FPM endpoint separately

fastcgi_pass can target a Unix socket, TCP host, or TCP port. A wrong or stopped endpoint more commonly produces a 502 than a 404, but it must be ruled out before interpreting mixed symptoms. Confirm that the socket file exists at the exact path in the active configuration, or that the configured host and port are reachable from NGINX. Then verify that the endpoint belongs to the PHP-FPM pool serving this application; multiple PHP versions often use different sockets.

Containers and separate hosts: the path must exist twice

In a containerized deployment, NGINX may see the application at /var/www/example/public while PHP-FPM sees it at /app/public. The file can therefore pass an NGINX-side check and still be unknown to PHP-FPM. Conversely, a path that exists in the PHP container does not help if NGINX’s try_files checks a different mount.

  • Run the shell existence test inside the NGINX environment and inside the PHP-FPM environment.
  • Compare ownership, permissions, symlink targets, and release mounts in both environments.
  • Use a shared absolute mount path where possible; otherwise set SCRIPT_FILENAME to the path PHP-FPM actually uses.
  • After a deployment switch, confirm that both processes have the same release and that an old container is not serving one side of the request.

A safe repair and reload procedure

  1. Copy the failing URL and host header from your evidence record.
  2. Run nginx -T and identify the exact server and PHP locations selected for that host.
  3. Resolve the URI against root or alias; verify the file, case, symlinks, and release path from the shell.
  4. Check that try_files is testing the intended candidate and that any front-controller fallback is intentional.
  5. Check fastcgi_pass against the actual PHP-FPM socket or TCP listener.
  6. Make SCRIPT_FILENAME valid in PHP-FPM’s filesystem view. Keep the query string handling supplied by the included FastCGI parameters.
  7. Validate syntax with nginx -t. Do not reload a configuration that has not passed this test.
  8. Reload NGINX using the service mechanism for the host, then repeat the same curl -i request.
  9. Inspect only the new access and error-log lines. Confirm that the status, upstream behavior, and resolved path now match the intended location.

Use controlled test files, then remove them

A known-good static file separates general server selection from PHP handling. A minimal, access-controlled info.php-style script can confirm that PHP-FPM is executing files, but it exposes environment details and should never remain publicly reachable. Protect the test location, run it only while diagnosing, and delete the diagnostic file when finished.

Test at least three cases: an existing PHP script, a deliberately nonexistent PHP path, and a directory URL whose index should be index.php. The first should execute, the second should fail at the intended layer with a clear 404, and the third should resolve according to the configured index and fallback rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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)

Additional checks that prevent recurring 404s

Once one request works, repeat the comparison with a script in a subdirectory and with a request that includes a query string. This catches configurations that happen to work only at the document root. Preserve the exact Host header in every test, because a correct edit in one virtual server does not change another server block selected by a different host name.

Review every inherited and included FastCGI parameter. A later SCRIPT_FILENAME assignment can override the value you intended to use, while a missing include can omit parameters needed to pass the query string. The final configuration printed by nginx -T, rather than an individual snippet, is the authoritative version to test.

When a deployment uses release directories, test immediately after the symlink switch. NGINX and PHP-FPM must resolve the same release, and both containers or hosts must have the corresponding mount. A stale process, old mount, or different working copy can recreate “Primary script unknown” after a configuration that was correct against the previous release.

How to choose between two proposed fixes

When administrators suggest different edits, evaluate them in this order:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Path correctness: Does the URI resolve to the real file under the active root or alias?
  2. Failure ownership: Does NGINX reject a missing script with try_files, or is it being sent to PHP-FPM first?
  3. Runtime visibility: Can PHP-FPM open the same absolute path, particularly across containers?
  4. Fallback behavior: Is /index.php an intentional front-controller route, or is it masking a typo?
  5. Observability: Do the logs and repeatable curl test make the selected location and path unambiguous?

The best fix is the smallest change that makes all five answers explicit. Replacing a working socket, adding unrelated rewrites, or disabling all 404 checks can hide the original mapping error and create a harder-to-diagnose production failure.

Frequently asked questions

Why does NGINX return 404 for an existing PHP file?

“Existing” may refer to a path on the host, not the path produced by the active server block. Confirm the selected root or alias, resolve the URI exactly, and check that result with ls -l. Also verify that the request is reaching the expected host block.

What does “No input file specified” mean?

It usually means PHP-FPM received a request but could not open the filename supplied in SCRIPT_FILENAME. Compare that absolute path inside the PHP-FPM environment, including containers or chroots, rather than checking only NGINX’s filesystem.

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

Should I always add try_files $fastcgi_script_name =404?

Use it after proving the path mapping. It is a useful boundary that rejects missing scripts in NGINX, but with an incorrect root, alias, or mount it will return 404 for valid scripts too.

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

Can a wrong PHP-FPM socket cause a 404?

A wrong or unavailable fastcgi_pass endpoint more commonly causes 502. Still check it when symptoms change, because a corrected path may expose an endpoint problem that was previously hidden by an NGINX-side 404.

Why do directory URLs fail while direct PHP URLs work?

Directory requests depend on the configured index behavior. Check the server’s index directive, the PHP location, and whether fastcgi_index index.php appends the expected script name for a URI ending in /.

Why does a typo load my application instead of returning 404?

The general location may intentionally redirect misses to /index.php?$query_string. Keep that front-controller fallback when the application requires it, but do not confuse it with validation of a direct PHP script path.

What should I test after changing the configuration?

Validate with nginx -t, reload, and repeat the identical curl -i request. Then test an existing script, a nonexistent script, and a directory URL. Inspect only the fresh access and error-log entries so the result is attributable to the change.

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

Is an info.php file safe to leave online?

No. Such a file can expose environment details. If used, restrict access during diagnosis and remove it as soon as the PHP-FPM test is complete.

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

Frequently Asked Questions

Why does NGINX return 404 for an existing PHP file?

The active server block may map the URI to a different path than the one you checked. Verify the Host header, root or alias, exact filename case, symlinks, and the final path shown by the active configuration.

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.

What causes “No input file specified” or “Primary script unknown”?

PHP-FPM cannot open the path in SCRIPT_FILENAME. Check that absolute path from inside the PHP-FPM container, host, or chroot and align mounts or the filename formula.

Should try_files be in the PHP location?

Once mapping is correct, try_files $fastcgi_script_name =404 rejects missing scripts before forwarding them, making the failure clearer. It should not be added blindly while root, alias, or mounts are 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.

Can an incorrect fastcgi_pass produce a 404?

It usually produces a 502, but verify the socket or TCP endpoint whenever the error changes after a path fix. Confirm it belongs to the PHP-FPM pool serving this application.

Why do slash-ending URLs behave differently?

Directory requests use index handling. Check index and fastcgi_index; the latter appends index.php when constructing the FastCGI script name for a URI ending in a slash.

How do I test the repair safely?

Run nginx -t, reload, repeat the same curl request, inspect fresh logs, and test an existing script, a missing script, and a directory URL. Remove any diagnostic info.php file afterward.

The Bottom Line

Trace the failing request through the active server block, resolve its URI against the real root or alias, and verify that file from the shell. Then make try_files, SCRIPT_FILENAME, and PHP-FPM’s filesystem view agree. Confirm the FastCGI endpoint, validate with nginx -t, reload, and retest with the same curl command while watching fresh logs. This separates an NGINX mapping 404 from a PHP-FPM path failure without masking either one.

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 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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.