October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Serve Static Files from Multiple Nginx Locations

Map several NGINX URL prefixes to different directories with predictable root or alias behavior, explicit try_files fallbacks, correct location precedence, and a practical verification checklist.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define one location block for each URL prefix, then choose root when the URI should remain part of the filesystem path and alias when the prefix should be replaced. Add try_files to make missing assets return a deliberate status, use ^~ when regular expressions must not override a prefix, and verify the result with nginx -t and representative requests.

The basic pattern: one URL prefix, one location

NGINX can serve several static trees from one virtual host. A request for game assets, downloadable patches, screenshots, or a default web root does not need to share one directory. Each URI prefix can have its own location block and filesystem mapping.

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.

This configuration gives three independent branches:

server {
    listen 80;
    server_name example.test;

    # /assets/app.css -> /srv/site/assets/app.css
    location ^~ /assets/ {
        root /srv/site;
        try_files $uri $uri/ =404;
    }

    # /downloads/manual.pdf -> /srv/files/manual.pdf
    location ^~ /downloads/ {
        alias /srv/files/;
        try_files $uri $uri/ =404;
    }

    # Other requests use the normal site tree
    location / {
        root /srv/site;
        try_files $uri $uri/ =404;
        index index.html;
    }
}

With root /srv/site, NGINX appends the complete request URI to the root directory. Therefore, /assets/app.css becomes /srv/site/assets/app.css. With alias /srv/files/ in location /downloads/, NGINX removes the matching /downloads/ prefix and appends the remainder to /srv/files/; /downloads/manual.pdf becomes /srv/files/manual.pdf.

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

The path behavior is determined by the active location. A request can be syntactically valid yet still produce a 404 if another location wins, if the resulting path is not what you expected, or if the worker process cannot read the file.

Choose root or alias deliberately

The two directives both identify a directory, but they construct paths differently. The NGINX documentation describes root as the directory used to search for a file; in practical terms, the request URI is appended. alias substitutes the part of the URI matched by the location.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Directive Location Request Filesystem result Best fit
root /srv/site; /assets/ /assets/app.css /srv/site/assets/app.css The URL hierarchy mirrors the directory hierarchy
alias /srv/files/; /downloads/ /downloads/manual.pdf /srv/files/manual.pdf A public prefix should not exist in the on-disk path

When root is simpler

Use root when the directory under the server root has the same structure as the public URL. It keeps related paths easy to predict: every URI component remains in the final path. A site rooted at /srv/site can expose /images/cover.jpg from /srv/site/images/cover.jpg without a separate mapping rule.

When alias is the right abstraction

Use alias for a mount point, archive directory, generated output directory, or other tree whose physical name does not include the public prefix. It is especially useful when /downloads/ should expose /srv/files/ directly rather than requiring /srv/files/downloads/.

Keep trailing slashes aligned

For a prefix directory, write the location and alias with matching trailing slashes: location /downloads/ and alias /srv/files/. This makes the prefix replacement unambiguous and avoids surprising path joins. If you intentionally use a location without a trailing slash, account for the exact URI text and test both the slash and no-slash forms.

Regular-expression aliases need extra care

alias is valid in a location context. In a regular-expression location, its value must identify the complete path required for the match, including any captured portion that your expression is meant to preserve. For maintainability, a plain prefix location is usually preferable for a whole static directory; reserve regex aliases for narrowly defined cases and test every capture.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Understand which location wins

Path mapping only matters after NGINX has selected a location. Prefix and regular-expression locations do not compete on a simple “first block wins” basis.

  1. NGINX checks exact matches such as location = /favicon.ico.
  2. It finds the longest matching prefix location.
  3. It evaluates regular-expression locations according to its documented matching order. A regex can take a request away from the prefix that appears most obvious.
  4. A prefix marked ^~ tells NGINX not to evaluate regular-expression locations for that branch once the prefix has won.

Exact matches are useful for one-off files, while ^~ is useful for an entire static tree that must not be intercepted by a broad extension rule.

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
location = /favicon.ico {
    root /srv/site;
}

location ^~ /assets/ {
    root /srv/site;
    try_files $uri =404;
}

# Keep regex locations narrow if you need one
location ~* \.(?:css|js)$ {
    root /srv/site;
    try_files $uri =404;
}

Without ^~, the final regular-expression block could handle a request that you expected to remain in the /assets/ branch. A broad expression such as location ~* for many extensions makes this problem more likely. Narrow the expression or protect the intended prefix.

Use try_files to make fallback behavior explicit

The try_files directive checks whether candidate files or directories exist under the active root or alias. NGINX internally redirects to the first candidate that exists. The final argument can be another URI, a named location, or an explicit status.

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.

Strict static branches

For assets and downloads, the safest default is usually:

try_files $uri $uri/ =404;

$uri checks the requested file, $uri/ permits a real directory request, and =404 stops processing with a not-found response when neither exists. This prevents a missing JavaScript bundle or patch archive from being silently routed to an unrelated application handler.

Fallback to another resource

A fallback URI is appropriate only when the product requires one. NGINX’s documented example uses try_files $uri /images/default.gif; to supply a default image. The fallback is an internal redirect, so the destination URI is looked up again and may select a different location.

location ^~ /avatars/ {
    alias /srv/avatars/;
    try_files $uri /images/default-avatar.png;
}

Use this deliberately: a default image is a valid product behavior, while serving an application shell for a missing asset often masks deployment errors.

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

Do not use an SPA fallback accidentally

Many single-page applications use try_files $uri /index.html;. That is appropriate for client-side routes, not for a strict static download or asset directory. In an assets block, use =404 unless the branch explicitly requires a fallback. Otherwise a typo such as /assets/app-typo.js can return HTML with a successful status, leaving the browser with a confusing MIME or parsing error.

Directory requests, indexes, and listings

When a URI ends in a slash, NGINX treats it as a directory request and checks the filenames listed by the index directive. The default index filename is index.html. If no listed file exists, NGINX returns 404 by default.

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)
location ^~ /manual/ {
    alias /srv/docs/;
    index index.html;
    try_files $uri $uri/ =404;
}

A request for /manual/ first maps to the aliased directory and then searches for index.html. Index resolution can cause an internal redirect and a second location lookup. If the index URI is handled by a different block, confirm that its root, alias, access rules, and fallback behavior are still appropriate.

autoindex on; enables a generated directory listing. Turn it on only when exposing a listing is intentional; a directory listing can reveal filenames that were not meant to be discoverable. If listings are not part of the design, leave autoindex off and provide explicit index files or return 404.

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

Build a multi-directory server step by step

1. Inventory the URL contract

  • List each public prefix, such as /assets/, /downloads/, and /screenshots/.
  • Write the intended filesystem directory beside each prefix.
  • Decide whether the URI should be appended (root) or removed and replaced (alias).
  • Decide whether a missing path must be a 404, a default resource, or an application route.

2. Check filesystem permissions

The NGINX worker account needs search permission on every parent directory and read permission on files it serves. A correct mapping still fails if the operating system denies traversal or reading. Keep private directories outside the mapped trees and do not make them readable merely to resolve a configuration mistake.

3. Add the most specific locations

Place exact and prefix branches for special trees, then add a general location / fallback. Use ^~ on prefixes that must not be intercepted by extension-based regex locations.

4. Set an explicit existence policy

Use try_files $uri $uri/ =404; for strict static content. If a fallback is required, document what it is and remember that it starts another location lookup.

5. Configure indexes only where needed

Set index in a branch that serves directories. Do not enable directory listings as a substitute for an index unless the listing is an intentional feature.

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

6. Validate before reloading

nginx -t

Run the test against the active configuration. Correct syntax, missing includes, and invalid paths reported by the command before reloading.

7. Reload gracefully

After a successful test, reload NGINX using the service manager used by your system. A graceful reload lets existing connections finish while workers adopt the new configuration. If the reload fails, keep the previous working configuration and inspect the service error output.

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

Verify every mapping, not just the home page

Use representative requests for each branch. Headers are enough to verify status and content type; verbose mode adds redirect and connection details.

curl -I http://example.test/assets/app.css
curl -I http://example.test/downloads/manual.pdf
curl -I http://example.test/downloads/missing.pdf
curl -I http://example.test/manual/
curl -v http://example.test/assets/file-that-might-match-a-regex.js
  • Known hit: request a file that definitely exists and confirm a successful response.
  • Known miss: request a random filename and confirm the intended 404 or documented fallback.
  • Directory index: request a trailing-slash directory and verify the expected index file is selected.
  • Regex collision: request a file whose extension could match another location and confirm that the intended prefix still wins.
  • Slash variant: check both the directory URI with and without its trailing slash if clients may use both forms.

Review the access and error logs while making these requests. The access log confirms which URI was received and what status was returned. The error log can reveal permission failures, missing files, invalid paths, and internal redirects. NGINX’s beginner guidance specifically recommends these logs when a configuration does not work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and precise fixes

The path contains the public prefix twice

Symptom: /downloads/manual.pdf produces a lookup such as /srv/files/downloads/manual.pdf, although the file is actually /srv/files/manual.pdf.

Cause: root /srv/files; appends the complete URI.

Fix: use alias /srv/files/; in location /downloads/, or create the matching downloads directory under the root if that is the intended layout.

A regex location unexpectedly handles the request

Symptom: a file under a carefully configured prefix receives different headers, a different root, or a different status.

Cause: a regular-expression location matched after the prefix selection.

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

Fix: add ^~ to the prefix when regex locations must not override it, or narrow the regex so it applies only to the files that need it.

An alias mapping returns 404 despite an existing file

Checks: confirm the alias includes the intended trailing slash, confirm that the URI prefix also ends in a slash, and inspect the error log for the path NGINX attempted. Then verify parent-directory traversal and file-read permissions for the worker account.

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.

Missing assets return the application shell

Cause: a broad try_files $uri /index.html; fallback is inherited or copied into a static branch.

Fix: give the static location its own try_files $uri $uri/ =404;. Keep the SPA fallback in the application route location only.

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

A directory request is a 404

Check that the directory exists under the active mapping, that the request includes the expected slash, and that the configured index filename exists and is readable. If an index triggers an internal redirect, verify the second location lookup rather than inspecting only the first block.

The configuration test passes but files still fail

nginx -t validates configuration syntax and referenced structure; it does not prove that every requested file exists or that the worker can read it. Use a known-hit request, inspect logs, and check the effective user, parent-directory permissions, symbolic links, and the exact path produced by root or alias.

A maintainable example for game-site assets and downloads

The following layout keeps frequently cached frontend files, large downloadable files, and the main document tree separate:

server {
    listen 80;
    server_name example.test;

    # Files physically stored beneath /srv/game-site/assets/
    location ^~ /assets/ {
        root /srv/game-site;
        try_files $uri =404;
    }

    # Public /patches/ maps directly to a mounted archive volume
    location ^~ /patches/ {
        alias /mnt/game-patches/;
        try_files $uri =404;
    }

    # Public screenshots are stored outside the document root
    location ^~ /screenshots/ {
        alias /srv/media/screenshots/;
        try_files $uri $uri/ =404;
    }

    # Main pages and deliberate client-side routing
    location / {
        root /srv/game-site;
        try_files $uri $uri/ /index.html;
        index index.html;
    }
}

Here, missing files in the three static branches remain 404s, while the final branch intentionally falls back to /index.html for client-side routes. Separating those policies prevents a typo in a patch or screenshot URL from being mistaken for a page route.

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

Operational details that prevent surprises

  • Keep mappings obvious: comment the URI-to-filesystem relationship next to each block, especially when an alias points to a mounted volume.
  • Prefer narrow regexes: extension rules are easy to make broader than intended and can interfere with prefix mappings.
  • Protect private trees: do not place secrets, source repositories, or upload staging directories beneath an exposed root or alias.
  • Test after directory changes: moving a physical directory requires checking both the configuration and operating-system permissions.
  • Use explicit statuses: =404 communicates that an absent static object is an error rather than an invitation to another handler.
  • Recheck internal redirects: indexes, fallback URIs, and named locations can select a second location with different rules.

The durable mental model is simple: first determine which location wins, then calculate its filesystem path, then apply try_files, index handling, and permissions. Debugging in that order is faster than changing directives at random.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

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

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