Define one location block for each public URL prefix, then choose root when the URL path mirrors the filesystem and alias when the prefix should map to a different directory. Add try_files with an explicit fallback, configure index for directory requests, and account for Nginx location precedence so the intended block handles every request.
Antihost offers Linux VPS plans with full root access, unlimited traffic on a 1 Gbps port and a 14-day free trial.
The basic pattern: one URL prefix, one location block
Nginx can serve several directory trees from one virtual host. A request is matched against the server’s location blocks; each block can map its URI space to a filesystem path or hand that space to another handler. For a static site, keep the mappings explicit and give each branch its own existence check.
As an Amazon Associate I earn from qualifying purchases.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11server {
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 other paths remain under the main site tree
location / {
root /srv/site;
try_files $uri $uri/ =404;
index index.html;
}
}
In the first block, Nginx appends the complete request URI to /srv/site. In the second, it removes the matching /downloads/ prefix and substitutes /srv/files/. The catch-all block serves the rest of the site from /srv/site. The ^~ modifier tells Nginx not to let a regular-expression location take over either static branch.
How Nginx turns a URI into a file path
root appends the complete URI
With root /srv/site;, Nginx joins the configured directory and the request URI. A request for /assets/app.css therefore resolves to /srv/site/assets/app.css. This is normally the clearest choice when the directory layout on disk deliberately mirrors the public URL tree.
#1 Best Overall
- [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.
A common mistake is using root /srv/files; inside location /downloads/ while expecting /downloads/manual.pdf to resolve to /srv/files/manual.pdf. It actually resolves to /srv/files/downloads/manual.pdf, because the whole URI is appended.
alias replaces the matched location prefix
With alias /srv/files/; in location /downloads/, Nginx replaces the matching URI portion with the alias path. The request /downloads/manual.pdf maps to /srv/files/manual.pdf; the public downloads directory does not need to exist on disk.
Recommended Free Tools
Keep trailing slashes aligned: use location /downloads/ with alias /srv/files/. The matching slash makes the path join predictable and avoids accidental concatenations such as /srv/filesmanual.pdf. The alias directive is valid in a location context. In a regular-expression location, its value must identify the complete path required by the match rather than relying on a simple prefix substitution.
| Request | Directive and location | Filesystem result | When to use |
|---|---|---|---|
/assets/app.css |
root /srv/site; in /assets/ |
/srv/site/assets/app.css |
The URL and disk tree have the same relative structure. |
/downloads/manual.pdf |
alias /srv/files/; in /downloads/ |
/srv/files/manual.pdf |
A public prefix exposes a directory whose on-disk name is different or absent. |
/index.html |
root /srv/site; in / |
/srv/site/index.html |
The default site tree handles all unmatched paths. |
Location precedence decides which mapping wins
The order of blocks in the file is not the whole matching algorithm. Nginx first evaluates exact and prefix locations, keeps the longest matching prefix, and then evaluates regular-expression locations according to its location-selection rules. A broad regex can therefore capture a request that appears to belong to a longer prefix.
Exact matches for single files
Use an exact location when one file needs a special rule:
location = /favicon.ico {
root /srv/site;
try_files $uri =404;
}
The = modifier matches only that URI. It is useful for a favicon, a health-check file, or another individual object that should not inherit a broad rule.
Prefix matches for directory trees
A plain prefix such as location /assets/ handles every URI beginning with that string. The longer prefix wins over location /, so assets are separated from the site’s general tree. Add ^~ when that prefix must win even if a regular-expression location also matches:
Rank #2
- 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
- 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
- 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
- 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
- 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
location ^~ /assets/ {
root /srv/site;
try_files $uri $uri/ =404;
}
Regular-expression locations require restraint
Regex locations use ~ for case-sensitive matching or ~* for case-insensitive matching. A rule such as location ~* .css$ is broad enough to intercept CSS requests from several URL trees. If that is not intentional, narrow the expression to the required prefix or protect the prefix with ^~. Keep regex rules specific because their interaction with prefix locations is a frequent source of surprising 404 responses and incorrect filesystem paths.
Build a multi-directory configuration step by step
- List the public prefixes. Write down the URI groups you intend to expose, such as
/assets/,/downloads/, and the root site. Include whether each group should serve files only or also allow directory requests. - Choose the mapping directive. Select
rootwhen the URI hierarchy should be appended to a common site directory. Selectaliaswhen the matching prefix should disappear before the remaining path is joined to a different directory. - Align slash conventions. For a directory prefix ending in
/, give a directory alias ending in/. This makes/downloads/manual.pdfresolve cleanly under/srv/files/. - Protect each branch with
try_files. Usetry_files $uri $uri/ =404;for strict static serving. It checks a file, then a directory, and returns a 404 when neither exists. - Set the directory index. Put
index index.html;in the location or server context when slash-ended requests should load that file. If you need another filename, list it explicitly. - Review competing locations. Search the active configuration for regex blocks, exact matches, and nested locations that could capture the same URI. Add
^~to a prefix when regex takeover would be wrong. - Validate and reload. Run
nginx -tagainst the active configuration. Only after a successful syntax check should you perform a graceful reload.
Plan URI and filesystem trees before writing locations
Start with a small mapping table rather than adding directives reactively. For every public prefix, record one example request, the directory that should contain the object, and whether the prefix itself appears in that directory name. If /assets/app.css belongs at /srv/site/assets/app.css, the tree mirrors the URL and root expresses that relationship directly. If the same request belongs at /srv/files/app.css, the public prefix is only a label and alias is the clearer mapping.
Keep each public directory represented by one authoritative location block. Overlapping prefixes make it harder to predict which rule wins, especially after a regex block is added later. A shared default site tree can be defined at the server level, while a location can provide the mapping needed for a distinct branch; the path is always resolved from the applicable root or alias in the current location or server context. Write the intended filesystem result beside each block during review so a duplicated prefix or missing separator is visible before deployment.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Use try_files to make fallback behavior explicit
try_files checks whether candidate files or directories exist under the active root or alias. It internally redirects to the first matching candidate. Its final argument can be a URI, a named location, or an explicit status such as =404.
Strict static paths
For assets, documents, and other paths where a missing object should remain missing, use:
try_files $uri $uri/ =404;
The first candidate tests the requested file. The second tests a directory. If neither exists, Nginx returns 404 instead of sending the request to an unrelated handler.
A deliberate fallback URI
A fallback can be useful when the behavior is part of the design. The documented pattern try_files $uri /images/default.gif; serves a default image when the requested file does not exist. Use such a fallback only where every missing request should receive that replacement.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #3
- [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
Do not apply an SPA fallback indiscriminately
try_files $uri /index.html; is common for client-side applications, but it changes the meaning of a missing asset: a request for a nonexistent stylesheet or image receives the application shell instead of a 404. Keep strict static locations on =404 and reserve an application fallback for the location that actually owns the application routes.
Directory requests, indexes, and listings
When a request ends with a slash, Nginx treats it as a directory request and searches the filenames named by index. The default index filename is index.html. If no configured index exists, Nginx returns 404 by default.
location ^~ /downloads/ {
alias /srv/files/;
index index.html;
try_files $uri $uri/ =404;
}
If /srv/files/index.html is absent, a request for /downloads/ does not automatically reveal the directory contents. To generate a listing, enable autoindex on; deliberately:
location ^~ /downloads/ {
alias /srv/files/;
autoindex on;
try_files $uri $uri/ =404;
}
A generated listing exposes filenames and should be enabled only when that disclosure is intended. Index resolution can cause an internal redirect and a second location lookup, so verify that the resulting URI still reaches the static block you designed rather than a regex or application handler.
A complete example with three independent trees
The following server separates published assets, downloadable files, and the main document tree. It uses strict 404 behavior in every branch and leaves directory listings disabled.
server {
listen 80;
server_name example.test;
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;
}
location / {
root /srv/site;
index index.html;
try_files $uri $uri/ =404;
}
}
Place the files accordingly: /srv/site/assets/ contains the asset tree, /srv/files/ contains downloadable files, and /srv/site/index.html is the main index. A request for /assets/app.css uses the first directory mapping; /downloads/manual.pdf uses the alias; / searches for the root index.
Why a location returns 404
The file is being looked up under the wrong directory
Inspect whether the block uses root or alias. If a prefix appears twice in the computed path, replace the mistaken root with an appropriately slashed alias. Conversely, if your disk really contains /srv/site/assets/, using alias /srv/site/ in /assets/ would remove the prefix and point to the wrong place; use root /srv/site there.
Rank #4
- 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.
A regex block captured the request
Look for broad location ~ or location ~* rules, especially extension-based rules. Add ^~ to the intended prefix or narrow the regex so it cannot capture unrelated trees.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →The alias and location slashes do not align
Compare the literal declarations. Prefer location /downloads/ with alias /srv/files/. Check the resulting path for missing or duplicated separators.
The fallback hides the real miss
If a branch uses try_files $uri /index.html, a missing file may return a valid-looking HTML response. Replace the fallback with =404 while diagnosing strict static paths.
The path exists but Nginx cannot read it
Check the configured error log and access log. The error log can reveal filesystem errors, while the access log confirms the requested URI and response status. Also verify that every parent directory can be traversed by the Nginx worker account and that the target file is readable. A filesystem permission problem can look like a missing file even when the pathname is correct.
The directory has no index
A slash-ended request needs a configured index file unless directory listing is intentionally enabled. Confirm the filename in index, check that it exists under the resolved directory, and remember that Nginx returns 404 when no index is found and autoindex is off.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteVerify every mapping before relying on it
Test each location, not just the homepage. The goal is to prove a known hit, a known miss, directory behavior, and precedence behavior.
- Syntax-check the active configuration: run
nginx -t. Fix every reported error before reloading. - Reload gracefully: apply the validated configuration without abruptly terminating existing connections.
- Request a known file from each branch: use
curl -I http://example.test/assets/app.cssand equivalent requests for the download and root trees. - Inspect a verbose response when needed: use
curl -vto see the request, status, and response headers while troubleshooting. - Request a known miss: confirm that a nonexistent asset or document returns 404 rather than an application shell or an unrelated fallback.
- Request a directory: check a slash-ended URI with an index file and another directory without one. Confirm the intended index or 404 behavior.
- Exercise a possible regex collision: request a filename whose extension could match a regex location and verify that the expected prefix block still handles it.
- Review logs: correlate the access-log status with error-log filesystem messages. This distinguishes matching errors, path construction errors, and permissions.
Design rules that keep configurations maintainable
- Give each public directory a clearly named prefix and a single authoritative location block.
- Use
rootfor mirrored URL and disk trees; usealiasonly when the prefix must be replaced. - Keep directory aliases and location prefixes consistent about trailing slashes.
- Prefer explicit
=404handling for static resources so failures are visible to browsers, monitoring, and logs. - Keep regular-expression locations narrow, and use
^~where a prefix must not be overridden. - Set
indexintentionally and leaveautoindexoff unless a listing is a deliberate feature. - After every change, syntax-check, reload, test representative hits and misses, and inspect both logs.
Quick decision guide
| Question | Recommended choice | Reason |
|---|---|---|
| Does the URL path mirror the directory tree? | root |
The complete URI is appended to one site directory. |
| Should a public prefix disappear from the disk path? | alias |
The matched location prefix is replaced by the alias directory. |
| Must a missing file fail clearly? | try_files $uri $uri/ =404; |
It checks existence and prevents unintended routing. |
| Should a slash-ended directory load a document? | index index.html; or another explicit filename |
Nginx searches the listed index files. |
| Should a prefix beat extension regex rules? | location ^~ /prefix/ |
The prefix is not passed to regex evaluation. |
| Should visitors see filenames in a directory? | autoindex on;, only when intentional |
It enables a generated directory listing instead of the normal no-index 404. |
Frequently Asked Questions
What is the practical difference between root and alias?
root appends the complete request URI to its directory, so /assets/app.css under root /srv/site becomes /srv/site/assets/app.css. alias replaces the matching location prefix, so /downloads/manual.pdf under alias /srv/files/ becomes /srv/files/manual.pdf.
Best Value
Why does my alias location return 404?
First check that the alias and location use matching trailing slashes, such as location /downloads/ with alias /srv/files/. Then verify the resulting filesystem path, the file permissions, and the error log. A regex location may also have captured the request instead.
Does the order of location blocks determine the winner?
Not by itself. Nginx keeps the longest matching prefix and then evaluates regular-expression locations according to its matching rules. Use an exact match for a single file and ^~ on a prefix when a regex must not override it.
What should the final try_files argument be for static files?
Use =404 when a missing file must remain a clear miss. The final argument can instead be a fallback URI or named location when that behavior is intentional, such as serving a documented default image.
Why does a directory request return 404 even though the directory exists?
A slash-ended request searches the filenames listed by index, with index.html as the default. If no index exists, Nginx returns 404 unless autoindex on; was deliberately enabled.
How can I verify that every static location works?
Run nginx -t, reload gracefully, and use curl -I or curl -v for known files, known misses, directory URLs, and filenames that could match regex rules. Correlate access and error logs while checking the results.
The Bottom Line
Use one explicit location per public tree. Choose root when the URI and disk layouts match, alias when the prefix should be replaced, and try_files $uri $uri/ =404; when missing static objects must fail clearly. Protect important prefixes with ^~, configure indexes deliberately, keep listings off unless required, and validate each branch with configuration tests, requests, and logs.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
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.




