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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Define one location block for each URL prefix, then choose root when the URL path mirrors the directory tree and alias when the URL prefix should be replaced by a different directory. Add try_files with an explicit fallback so missing assets return a predictable status instead of being sent to an unrelated application route.

The following configuration maps /assets/ into a subdirectory of the site root, maps /downloads/ to a separate filesystem directory, and serves every other URI from the main site directory:

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

A working configuration for several static directories

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

    # All remaining requests use the main site directory
    location / {
        root /srv/site;
        try_files $uri $uri/ =404;
        index index.html;
    }
}

With this server, a request for /assets/app.css is searched for under /srv/site/assets/app.css. A request for /downloads/manual.pdf is searched for under /srv/files/manual.pdf; the /downloads/ portion is not appended to the disk path. A request that matches none of those prefixes falls through to location / and is searched for under /srv/site.

The ^~ modifier matters when regular-expression locations also exist. It tells Nginx to use the longest matching prefix without testing regex locations for that request. If you do not need regex locations, ordinary prefix locations are sufficient, but using ^~ documents and protects the intended branch when a larger configuration later gains regex rules.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.

How Nginx maps a URI to a file

Nginx separates the public request URI from the filesystem path used to find content. The active location determines which mapping rule applies, and the root or alias in that context determines the resulting path.

Prefix locations

A prefix location matches URIs beginning with the text in the location declaration. For example, location /assets/ can handle CSS, JavaScript, images, and other files whose request path starts with /assets/. Nginx keeps the longest matching prefix before it considers regex locations.

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.

Regular-expression locations

A location beginning with ~ uses a case-sensitive regular expression; ~* uses a case-insensitive expression. Regex locations are evaluated after prefix matching and can take a request away from the prefix block that appears to match it. Broad extension rules such as a catch-all location ~ can therefore cause surprising mappings.

Exact locations

An exact location, written with =, matches one URI only. It is useful for a single well-known file, such as:

location = /favicon.ico {
    root /srv/site;
    try_files $uri =404;
}

Use an exact match when one file needs behavior that should not affect the rest of a directory.

Root versus alias

The most common source of a static-file 404 is choosing the wrong path directive. Both directives identify a filesystem directory, but they join that directory to the request in different ways.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
Directive Path behavior Best fit Example
root Appends the complete request URI to the configured directory. The URL tree and disk tree have the same relative structure. location /assets/ { root /srv/site; } maps /assets/app.css to /srv/site/assets/app.css.
alias Replaces the matching location portion with the configured path. A public prefix should expose a directory that does not contain that prefix on disk. location /downloads/ { alias /srv/files/; } maps /downloads/manual.pdf to /srv/files/manual.pdf.

When root is the simpler choice

Use root when the directory layout already mirrors the URL layout. If files live in /srv/site/assets/ and clients request them as /assets/..., root /srv/site; expresses that relationship directly. The request URI remains intact after the root directory is prepended.

When alias is required

Use alias when the URL prefix is only a public name. In the example, clients see /downloads/, but the files are stored directly in /srv/files/, not in /srv/files/downloads/. Alias removes the matching location prefix before joining the remainder to its target path.

Keep trailing slashes aligned

For a directory mapping, keep the location and alias slash conventions aligned: location /downloads/ with alias /srv/files/. A mismatch can produce unexpected path joins and make an otherwise present file appear missing. If you intentionally use a location without a trailing slash, design the alias and test the resulting path explicitly rather than assuming the directory form will be inferred.

Alias and regular expressions

alias is valid in a location context. When it is used with a regular-expression location, the alias value must identify the complete path needed for the match. Regex captures and the final alias path must be designed together; a directory-style alias that works for a prefix location should not be copied into a regex block without checking how the expression captures the requested filename.

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

Build the configuration step by step

  1. List the public URL groups. Write down every prefix that should map to a different directory, such as /assets/, /downloads/, or /media/. Decide whether each prefix mirrors a directory below one common site root or points somewhere independent.
  2. Choose the mapping directive. Select root for mirrored trees and alias for prefix replacement. Record the exact filesystem directory, including whether it ends with a slash.
  3. Create one location per prefix. Put the most specific prefixes in separate blocks. Prefix order in the file does not replace Nginx’s matching rules; the longest matching prefix is retained automatically.
  4. Set an explicit missing-file policy. For strict static delivery, use try_files $uri $uri/ =404;. This checks the requested file or directory and returns 404 when neither exists.
  5. Define directory indexes deliberately. Set index index.html; where a directory request should load that file. If no configured index exists, Nginx returns 404 by default.
  6. Add a catch-all only for the intended site. A final location / can serve the primary site root. Do not let it silently turn missing files from a special static branch into an application response unless that behavior is intentional.
  7. Validate before reloading. Run nginx -t against the active configuration. Correct syntax and path errors before applying the change.
  8. Reload gracefully. Reload Nginx using the service-management command appropriate to your installation, then test representative requests rather than assuming a successful reload proves that path mapping is correct.

Use try_files to control fallbacks

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

Strict static files

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

This form serves an existing file, allows an existing directory to proceed to index processing, and returns 404 for a missing path. It prevents a typo in an asset URL from being handled by an unrelated fallback.

Rank #3
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

A deliberate default resource

A fallback URI is appropriate when the product requirement calls for a default resource. For example, an image branch can use:

location ^~ /images/ {
    root /srv/site;
    try_files $uri /images/default.gif;
}

If the requested image is absent, Nginx internally redirects to /images/default.gif. Make sure that fallback URI is itself served by a location and that the default file exists.

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

Why an SPA fallback can be wrong here

Many single-page applications use try_files $uri /index.html so client-side routes reach the application shell. That behavior is not a safe default for a static asset directory: a missing stylesheet, script, or download may receive HTML instead of a 404. Use =404 for branches where the requested file must exist, and reserve an application fallback for the location that is intentionally responsible for application routes.

Directory requests and index files

When a request ends in a slash, Nginx treats it as a directory request and searches the filenames listed by the index directive. The default index filename is index.html; setting the directive makes the choice explicit:

location / {
    root /srv/site;
    index index.html;
    try_files $uri $uri/ =404;
}

If no index file is found, Nginx returns 404 by default. It does not automatically expose a directory listing.

Intentional listings

autoindex on; enables a generated directory listing. Turn it on only for a directory where listing its contents is an intentional part of the service. A download area that should require a known filename should keep autoindex disabled and rely on explicit links or an application-managed index.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Internal redirects and a second location lookup

Index resolution can trigger an internal redirect. The resulting URI may be looked up again, so confirm that the index request still reaches the intended static block. This matters when a broad regex location, a special root, or an application fallback also exists in the server.

Understand location precedence before debugging

Location selection follows a defined sequence rather than simply using the first block written in the configuration:

  1. Nginx checks exact matches and uses one immediately when present.
  2. It compares prefix locations and retains the longest matching prefix.
  3. Unless the selected prefix uses ^~, Nginx evaluates regex locations in configuration order.
  4. If a regex matches, that regex location handles the request; otherwise the retained prefix handles it.

This explains why a request under /downloads/ can unexpectedly enter an extension-based regex location. Narrow regex patterns to the files they truly own, or mark the static prefix ^~ when regex locations must not override it.

Example of an override

location ^~ /downloads/ {
    alias /srv/files/;
    try_files $uri $uri/ =404;
}

# This broad rule can capture requests if the prefix lacks ^~
location ~* .(css|js)$ {
    root /srv/legacy;
}

With ^~, a request such as /downloads/readme.js remains in the download branch. Without it, the regex can win and cause Nginx to search under the legacy root instead.

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

Diagnose common 404 and wrong-file problems

Symptom Likely cause Correction
A file appears under /srv/files/downloads/... in your reasoning, but the real file is under /srv/files/.... root was used where the URL prefix should be removed. Use alias /srv/files/; in location /downloads/.
A request under a special prefix is handled by an extension rule. A regex location superseded the prefix. Add ^~ to the prefix or narrow the regex.
Every file in an alias directory returns 404. The location and alias trailing-slash forms do not align, or the alias target is not the directory you intended. Use matching directory forms, then inspect the effective path and error log.
Missing assets return the site’s HTML shell. try_files ends in an application fallback such as /index.html. Use try_files $uri $uri/ =404; for a strict static branch.
A directory URL returns 404 even though the directory exists. No configured index file exists in that directory. Set the intended index filename, add the file, or intentionally enable autoindex.
Nginx reports a path or access failure. The configured filesystem path is wrong, or the worker cannot access the target. Check the active error log and access log, verify the resolved path, and correct the configuration or filesystem access.

Use logs to distinguish mapping from availability

An access log shows which URI was requested and the status returned. The error log provides the filesystem error and the path Nginx attempted. Check both while requesting one known-good file and one known-missing file. A 404 caused by a wrong root or alias looks different from a configuration that never reaches the intended location.

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

Verify every location after a change

Do not test only the homepage. Exercise each mapping and each branch that can change the result:

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
  1. Run nginx -t and fix any reported syntax or include-file error.
  2. Reload Nginx gracefully after the test succeeds.
  3. Request a known file from every static prefix with headers only, for example curl -I http://example.test/assets/app.css and curl -I http://example.test/downloads/manual.pdf.
  4. Request a known-missing file from each prefix and confirm that the intended status, normally 404, is returned.
  5. Request a directory with a trailing slash and verify that the expected index file is selected.
  6. Request a path with an extension that could match a regex location, such as a JavaScript file below /downloads/, and verify that it remains in the intended branch.
  7. Use curl -v when you need to inspect redirects and response headers, while watching the access and error logs for the same request.

Testing a hit, a miss, an index request, and a possible regex collision gives you evidence for both path construction and location precedence.

Patterns you can adapt

Several mirrored directories under one root

server {
    listen 80;
    server_name example.test;

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

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

    location / {
        root /srv/site;
        index index.html;
        try_files $uri $uri/ =404;
    }
}

Here both special branches use root because the disk layout contains matching assets and images directories below /srv/site.

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

Separate storage for public downloads

server {
    listen 80;
    server_name example.test;

    location ^~ /downloads/ {
        alias /srv/files/;
        try_files $uri $uri/ =404;
    }

    location / {
        root /srv/site;
        index index.html;
        try_files $uri $uri/ =404;
    }
}

This keeps downloadable files outside the main site tree while presenting a stable public prefix. The alias target is still part of the server’s filesystem, so verify that the configured directory contains only files intended for that URL space.

One-file exception plus multiple directories

location = /favicon.ico {
    root /srv/site;
    try_files $uri =404;
}

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

location ^~ /downloads/ {
    alias /srv/files/;
    try_files $uri $uri/ =404;
}

The exact favicon rule is evaluated for that URI only; the directory prefixes continue to handle their own trees.

A decision checklist for new mappings

  • Does the URL prefix exist as a directory below one common filesystem root? If yes, start with root.
  • Should the URL prefix disappear from the disk path? If yes, use alias.
  • Do the location and alias use matching trailing-slash forms?
  • Could a regex location match this request? If yes, narrow it or use ^~.
  • Should a missing file be a hard 404, a default resource, or an application route? Set the final try_files argument accordingly.
  • Should a directory request load an index? Set index and ensure that file exists.
  • Is a directory listing intentional? Enable autoindex only for that explicit use case.
  • Have you tested a hit, a miss, a directory, and a regex-collision path after reloading?

Once these decisions are explicit, adding another static location is mechanical: define its public prefix, select the correct path directive, set the fallback policy, and verify the resulting filesystem path with logs and representative requests.

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.

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