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×
FREEDOM251

Freedom251 › Blog › 404 troubleshooting

Fix Nginx Not Serving Static and Media Images

By Freedom251 Team · · 12 min read

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

If NGINX returns 404 or 403 for a CSS file, JavaScript bundle, uploaded photo, or other image, start with the URL-to-filesystem mapping—not with permissions or application code. NGINX selects the most specific location, builds a local path from root or alias, and then checks that path. A wrong location, an unexpected prefix in the path, filename case differences, an unreadable directory, or an omitted MIME map explains most failures.

Record one failing URL and status, identify the active location, calculate the exact path NGINX should open, validate the loaded configuration, and then use the access and error logs to confirm the result. The procedure below also shows when to use root, when alias is appropriate, and how to make missing-file behavior explicit with try_files.

As an Amazon Associate I earn from qualifying purchases.

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.

How NGINX turns an image URL into a file request

For a request such as /images/a.png, NGINX first chooses a server block and then the most specific matching location. That location determines whether the request is served from disk, passed to an application, redirected, or rejected. The active file-serving directive then determines the local pathname.

root appends the request URI

The root directive specifies the directory used to search for a file. NGINX appends the request URI to that directory. With root /www/data;, a request for /images/a.png resolves to /www/data/images/a.png. A request for /static/css/site.css resolves to /www/data/static/css/site.css.

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

This is usually the clearest choice when your URL tree mirrors your directory tree. The directory named by root should contain the URL prefixes as subdirectories, and the spelling and capitalization of every component must match the request.

alias replaces the matched location prefix

The alias directive maps a location directly to another filesystem path. Instead of appending the complete URI to a common root, NGINX replaces the matched location prefix with the alias target. For example, location /media/ { alias /srv/app/uploads/; } is intended to map /media/photo.jpg to /srv/app/uploads/photo.jpg.

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

The trailing-slash convention matters. A location written as /media/ should normally use an alias ending in /. Validate the mapping against an actual filename; replacing root with alias does not preserve the same path construction.

Location selection can defeat an apparently correct rule

A broad prefix location may not be the rule that handles the request. NGINX evaluates prefix locations and regular-expression locations according to its matching rules; a matching regular-expression location can take precedence over an ordinary prefix location. Inspect every candidate, including snippets included from another file. If a static location is meant to win over regular expressions, verify whether the configuration uses the intended precedence, such as a carefully chosen ^~ prefix, and test the result rather than assuming the visible block is active.

Eight-step diagnostic workflow

  1. Capture one failing request. Copy the exact image URL from the browser and record its status in developer tools, or run curl -I http://127.0.0.1/static/images/logo.png. Keep the path, query string, status, and response headers together; changing several URLs at once makes the diagnosis ambiguous.
  2. Find the active server block. Determine which listening address, port, hostname, and server block receive the request. A correct static rule in a different virtual host cannot serve the failing request.
  3. Find the most specific location. Check exact, prefix, and regular-expression locations. Look for a regex rule that captures image extensions or a generic application fallback that is selected instead of the static block.
  4. Compute the expected filesystem path. For root /var/www/site; and /images/a.png, test /var/www/site/images/a.png. For an alias, replace the matched location prefix with the alias directory and retain only the unmatched suffix. Compare the resulting path with the real file, including capitalization.
  5. Validate the configuration before reloading. Run nginx -t. Correct syntax errors, duplicate or unintended locations, and missing included files before any reload. Use nginx -V to see the compiled configuration path when the service may be reading a different tree than the one you edited.
  6. Make file existence explicit. In a static location, use try_files $uri =404; (or try_files $uri $uri/ =404; when directories should also be considered). The directive checks whether the candidate file or directory exists and returns the specified fallback when it does not. If your application must handle missing paths, use its documented fallback instead of silently routing every miss.
  7. Read both logs. Match the request in access.log to confirm the URI and status, then inspect error.log for the filesystem open failure. The error usually reveals the path NGINX actually tried, which can expose an extra URL prefix, a typo, a wrong mount point, or an access denial.
  8. Retest the exact URL. Check the status, Content-Type, and body length with curl -I or browser tools. A successful status alone is not enough if the response is an HTML application page with an image URL.

Use the status code to choose the next check

Status or symptom First interpretation Checks to perform
404 Not Found NGINX did not find the requested file at the path selected by the active configuration. Recalculate root/alias mapping; verify the location selected, filename case, mount point, and whether the file exists.
403 Forbidden The path may exist, but NGINX cannot traverse a directory or read the file, or a host security policy blocks access. Check execute permission on every parent directory, read permission on the file, the account running NGINX, mount options, and the host’s security policy. Confirm the log identifies an actual permission denial.
200 with an image that does not render The response may be an HTML error page, an application response, or a file sent with an unsuitable media type. Inspect the response body, Content-Type, and body length. Confirm the request reached the intended static location and that MIME mappings are loaded.
301 or 302 on an asset A redirect is changing the URL before the file lookup, often because another location or canonicalization rule matches first. Follow the redirect in developer tools, inspect the destination path, and identify the location that generated it before changing the static rule.

Known-good configurations for common layouts

Use root when URL directories exist below one site root

In this layout, the filesystem contains /var/www/site/static/ and /var/www/site/media/, and the public URLs are /static/ and /media/.

server {
    root /var/www/site;

    location /static/ {
        try_files $uri =404;
    }

    location /media/ {
        try_files $uri =404;
    }
}

A request for /static/app.css therefore checks /var/www/site/static/app.css. A request for /media/photos/2026/01/portrait.jpg checks /var/www/site/media/photos/2026/01/portrait.jpg. If your files are actually stored directly in another directory, this configuration will consistently return a miss because the appended URL prefix is part of the path.

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

Use alias when a URL prefix points outside the site root

When uploads live at /srv/app/uploads/ but must be public under /media/, map that location explicitly:

location /media/ {
    alias /srv/app/uploads/;
    try_files $uri =404;
}

Validate the result with a real file such as /srv/app/uploads/photo.jpg and the corresponding URL /media/photo.jpg. Keep the slash convention consistent between the location and alias. If the error log shows a duplicated prefix or an unexpected suffix, stop and correct the mapping rather than adding more rewrite rules.

Keep static and application locations separate

Static assets should have a location whose behavior is obvious. A generic application fallback can otherwise turn a missing image into a successful HTML response. Put the static and media locations above broad application rules in the configuration for readability, then confirm actual matching behavior with logs and a test request.

Make try_files work for the behavior you want

The try_files directive checks candidate files or directories in order. try_files $uri =404; tests the URI-derived path and returns a 404 immediately when it is absent. This makes a typo or missing deployment file distinguishable from an application route.

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

Adding $uri/ allows a directory match before the final status:

try_files $uri $uri/ =404;

Use an application fallback only when the application is intentionally responsible for the request. A fallback can be appropriate for a front-controller site, but it should not mask missing images that ought to be served directly. When a fallback is used, verify the returned body and media type; a 200 status containing an HTML error page is still a broken image response.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [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

With an alias, do not assume that a try_files line behaves like one under root. The alias replacement and location suffix must be validated against a real filename. If the log shows that NGINX is testing the wrong path, fix the location/alias relationship and retest rather than layering rewrites on top.

Inspect the configuration NGINX actually loaded

Editing a file does not guarantee that the running worker uses it. Distribution packages commonly include a main file, virtual-host files, snippets, and MIME definitions. An included file can add a later location, override a setting, or define a regex that captures image requests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run nginx -t and note the configuration file named in the output.
  2. Run nginx -V when you need the compiled-in configuration path or build arguments.
  3. Open the main file and follow every include directive used by the relevant HTTP and server contexts.
  4. Search the loaded configuration tree for the failing URI prefix, image extensions, root, alias, try_files, rewrites, and proxy or FastCGI fallbacks.
  5. After a successful test, reload NGINX using the service method for your system, then send the same request again and compare the logs.

Do not troubleshoot a stale configuration by changing filesystem ownership or adding permissive rules. The effective configuration and the error log should explain which path and rule are involved first.

Check the filesystem, case, mounts, and permissions

Verify the file and every directory component

On case-sensitive filesystems, Logo.PNG, logo.png, and logo.PNG are different names. Compare the URL character for character with the deployed filename. Check nested directories as well as the final file; a missing upload subdirectory produces the same kind of path miss as a missing image.

Confirm that the directory containing the files is mounted in the NGINX runtime environment. A container or chroot can have a path that exists on the host but not inside the process’s filesystem namespace. The error log’s open path and the process’s view of that path must agree.

Interpret 403 as a traversal or policy problem

Reading a file requires more than read permission on the final file. NGINX’s worker account also needs permission to traverse each parent directory. Check the account used by the worker, directory execute permissions, file read permissions, and any host security policy that can deny access even when ordinary mode bits look correct. Grant the narrowest access needed for the static tree; do not solve a location mistake by making the entire filesystem world-readable.

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

Watch for generated and uploaded files

Static bundles may be created during deployment while media files are written by a separate process. Verify that the generated output and upload directory are the same paths referenced by the active configuration. If a deployment changed the directory name or mount point, update the mapping and reload after nginx -t succeeds.

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

Confirm MIME mappings for image extensions

Once NGINX finds a file, it still needs to send an appropriate media type. Confirm that the HTTP context loads the MIME map and that it contains mappings for the image extensions you serve. NGINX’s documented mappings include image/gif and image/jpeg; your configuration should likewise cover every extension used by the site.

http {
    include mime.types;
    default_type application/octet-stream;

    # server blocks and their locations follow here
}

Check the response headers with curl -I. If a known JPEG is returned as a generic binary type or as HTML, inspect the loaded MIME include and the selected location. Do not use a MIME change to hide a 404: the file must first be found and read successfully.

Root versus alias: choose by path design

Decision point root alias
Filesystem construction Appends the request URI to the root directory. Replaces the matched location prefix with the alias target.
Best fit URL prefixes correspond to directories beneath one site root. A URL prefix must expose a different directory, such as an upload tree outside the site root.
Path validation Check that the full URI path exists below the root. Check the alias target plus only the unmatched URI suffix.
Common mistake Files are stored without the URL prefix, so NGINX looks one directory too deep. Slashes or the replaced prefix are miscalculated, producing a duplicated or truncated path.
Interaction with try_files The URI-derived candidate normally follows the root mapping. Validate the candidate against an actual filename; alias path construction can differ from root behavior.

Choose one model per location and document the intended mapping in a comment. Switching directives without checking a real request path is a common way to turn a known-good location into a 404.

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

Direct static serving or application fallback?

Approach Use it when What to verify
Direct NGINX serving The file should exist on disk and be returned unchanged. Worker access to the static tree, correct path mapping, MIME type, and the desired cache behavior for those assets.
Application fallback The application intentionally generates or authorizes the response for a missing or virtual path. The fallback is selected only after the intended file check, and missing images do not become misleading 200 HTML responses.

For ordinary static and uploaded images, direct serving with an explicit 404 is easier to diagnose. An application fallback is a deliberate routing decision, not a repair for an incorrect root or alias.

Common failure patterns and their fixes

The URL prefix is duplicated

Symptom: the error log shows a path such as /var/www/site/media/media/photo.jpg when the file exists at /var/www/site/media/photo.jpg. Cause: the configuration or rewrite added the prefix twice. Remove the extra rewrite or use a mapping whose construction matches the chosen directive.

The file is one directory above or below the computed path

Symptom: every asset in a location returns 404, while the files are present in a neighboring directory. Cause: root appended a URL prefix that is not present on disk, or an alias target points at the parent instead of the upload directory. Recalculate one concrete request and change only the directive that produced the wrong path.

A regex location captures image requests

Symptom: the static block looks correct, but the request reaches an application or returns a different status. Cause: a regular-expression location for extensions or a broad fallback wins during location selection. Inspect all matching locations, adjust precedence deliberately, and verify with a new request.

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

The image returns an HTML page with status 200

Symptom: the browser reports a decoding error, while the network panel shows status 200 and a body that begins like an HTML document. Cause: the request fell through to an application route. Add an explicit file check in the static location and reserve the fallback for paths the application owns.

Only some filenames fail

Symptom: lowercase names work but names containing capitals, spaces, or non-ASCII characters fail. Cause: URL encoding or case does not match the filesystem entry. Compare the decoded request path and deployed filename, and generate URLs that preserve the actual name or use a consistent normalized naming scheme.

It worked before a deployment or restart

Symptom: the same URL changes behavior after a release, mount change, or reload. Cause: the effective include tree, compiled configuration path, generated asset directory, or mounted volume changed. Run nginx -V, validate with nginx -t, inspect the logs, and compare the path NGINX opens with the new deployment layout.

A repeatable verification checklist

  • One exact failing URL and its current status are recorded.
  • The receiving server block and most specific location are identified.
  • Any regex location that could override the prefix location has been checked.
  • The expected path has been calculated using the actual root or alias rule.
  • The file exists at that exact path with matching case.
  • Every parent directory is traversable by the NGINX worker account, and the file is readable.
  • The path is present inside the runtime environment and mounted where the configuration expects it.
  • nginx -t succeeds, and included files have been inspected.
  • try_files returns an intentional 404 or invokes an intentional application fallback.
  • access.log and error.log show the same request, status, and open-path result.
  • The HTTP context loads the MIME map for the image extensions in use.
  • A final request confirms the expected status, Content-Type, and non-HTML response body.

What a correct repair looks like

A repaired static location has a predictable relationship between URL and disk path. With root, the URL prefix is a real directory below the root. With alias, the location prefix is replaced by the intended target and the slash convention is consistent. try_files states what happens when the file is absent, logs show the expected open path, permissions allow traversal and reading, and the response carries the MIME type for the file extension.

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

If the same URL still fails after these checks, keep the failing request, calculated path, selected location, configuration-test output, and matching log lines together. Those five pieces identify whether the remaining problem is routing, path construction, filesystem state, access control, or response typing without guesswork.

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.

404 troubleshootingLinux administrationMedia uploadsNGINXstatic filesweb server

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.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.