Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Use NGINX Location Alias With Rails

A practical guide to mapping Rails public/assets with NGINX alias, choosing root or alias, separating static and dynamic requests, and fixing deployment and permission errors.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use an NGINX alias when the URL path and the directory on disk are not the same path, such as mapping /assets/ to a Rails release’s public/assets/. Use root when the request URI should be appended to one document root. In a typical Rails deployment, NGINX serves precompiled assets directly and proxies every other request to Rails.

Understand the path NGINX is resolving

Every static request has two names: the URI requested by the browser and the filesystem path NGINX must open. The choice between root and alias determines how NGINX converts the first into the second.

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.
Directive How NGINX builds the path Example result for /assets/application.css Best fit
root Appends the complete request URI to the configured directory. /srv/myapp/current/public/assets/application.css when the root is /srv/myapp/current/public. The filesystem mirrors the URL structure.
alias Replaces the location prefix with the configured target directory. /srv/myapp/current/public/assets/application.css when /assets/ is aliased to /srv/myapp/current/public/assets/. The URL prefix and directory have different names or locations.

With a matching location /assets/, an alias of /srv/myapp/current/public/assets/ removes the /assets/ part of the URI and substitutes that directory. Thus, /assets/application-abc123.css resolves to /srv/myapp/current/public/assets/application-abc123.css. The trailing slash on both the location and alias makes that replacement unambiguous.

Do not choose alias merely because the request is for a static file. Choose it when you need replacement semantics. If your public directory is /srv/myapp/current/public and it contains an assets subdirectory that should correspond directly to /assets/, root is also valid.

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

Prepare Rails assets before configuring NGINX

Rails production assets are normally fingerprinted and written to public/assets during precompilation. NGINX cannot serve a source file that was never compiled into the directory named by the configuration.

  1. Run the production precompile command from the release that will be deployed:
RAILS_ENV=production SECRET_KEY_BASE_DUMMY=1 rails assets:precompile
  1. Confirm that the generated, fingerprinted files are inside the same release directory used by the NGINX alias. For the example configuration below, a file must exist under /srv/myapp/current/public/assets/, not only in a source tree or an older release.
  2. Ensure the NGINX worker can traverse every parent directory and read the asset files. A correct URI-to-path calculation still produces a 404 if a directory permission prevents traversal.

Rails documents direct web-server delivery of precompiled assets and gives a one-year cache example. Fingerprinted names allow clients and intermediaries to retain an unchanged file for a long time; a new digest produces a new URL when the content changes.

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.

Working configuration: alias for assets, proxy for Rails

This pattern keeps public, immutable assets out of the Rails request path while sending application routes to the Rails server:

upstream rails_app {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name example.com;

    location /assets/ {
        alias /srv/myapp/current/public/assets/;
        expires 1y;
        add_header Cache-Control public;
        add_header ETag "";
    }

    location / {
        proxy_pass http://rails_app;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

The asset block is deliberately narrow. A request such as /assets/application-abc123.css is handled by NGINX, while a request such as /orders/42 falls through to location / and is proxied to Rails. The proxy headers preserve the original host, forwarding chain, and request scheme that the application may need when generating URLs or interpreting the request.

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.

expires 1y and Cache-Control public express a long-lived public cache policy suitable for fingerprinted files. The empty ETag header in this example follows Rails’ documented NGINX cache configuration. Apply that policy only to files whose names change when their contents change; do not blindly give mutable responses a one-year lifetime.

Replace example.com, the Rails port, and the release path with values from your deployment. The directive semantics do not verify that your directory exists, so check the mapping against the active release before reloading NGINX.

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

When root is the better directive

If the URI hierarchy is already represented below one document root, the equivalent configuration is simpler:

location /assets/ {
    root /srv/myapp/current/public;
}

For a request beginning with /assets/, NGINX appends that complete URI to /srv/myapp/current/public, yielding a path beneath public/assets. No prefix replacement is needed because the URL and directory names mirror each other.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [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

Use alias for a mapping such as this:

location /downloads/ {
    alias /srv/myapp/shared/uploads/;
}

Here, the public name /downloads/ does not match the directory name uploads. With root, NGINX would look for a directory named downloads beneath the root; with alias, it substitutes the intended directory.

Question Prefer root Prefer alias
Does the URL prefix mirror a directory beneath one document root? Yes; appending the URI is the desired result. No; the URI prefix must be replaced.
Is the location a directory-style prefix? Works for a prefix whose hierarchy matches disk. Works when the prefix maps to a specific, differently named directory.
Does a fallback need to check whether a file exists? Use try_files with the active root when appropriate. Use try_files with the active alias when appropriate.
Are the files public or authorization-protected? Neither directive supplies authorization. Public files can be exposed by either; protected files should be authorized by Rails and transferred with the NGINX integration described below.
Will the Rails release directory change on deployment? Point the directive at a stable current-release path or update it to the new release and validate the configuration before reload.

Make location matching predictable

NGINX supports prefix and regular-expression locations. It finds the longest matching prefix before processing regular-expression locations. That allows a specific assets location and a general proxy location to coexist, but another regular-expression block can still affect which handler ultimately serves a request.

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

Keep the public alias as narrowly scoped as possible. Do not alias an entire release directory when only public/assets is intended for browser access. A broad alias can expose files that Rails would normally protect or that were never meant to be public.

When an asset unexpectedly reaches Rails, inspect all locations in the active server block rather than assuming the visible location /assets/ is the one handling the request. When an unrelated URI is being served from the asset directory, narrow the alias and review regular-expression locations for an unintended match.

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.

Use try_files when existence checks matter

NGINX’s try_files directive checks candidate paths using the active root or alias. If a candidate exists, NGINX internally redirects to it; if none exists, the directive can return a final status such as =404.

location /assets/ {
    alias /srv/myapp/current/public/assets/;
    try_files $uri =404;
    expires 1y;
    add_header Cache-Control public;
    add_header ETag "";
}

This form prevents a missing fingerprinted file from being handed to the Rails catch-all. Whether you want a missing asset to become a hard 404 or to follow an application fallback is a deployment decision; make that behavior explicit instead of relying on an accidental location match. Test the exact URI with the active configuration because alias and variable expansion must resolve to the directory you expect.

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

Account for release directories and deploys

Rails deployments commonly place each build in a release directory and expose the selected build through a path such as /srv/myapp/current. The alias must resolve to the release that contains the files referenced by the HTML being served.

  • If HTML references application-oldhash.css but the alias points to a release containing only application-newhash.css, the old URL returns 404.
  • If precompilation ran in one release while NGINX still points to another, source assets may exist in the application checkout while the public path remains empty.
  • If the alias is changed during a deployment, run nginx -t and reload only after the new directory and its permissions are ready.
  • A stable current path avoids editing the NGINX file for every release, but you still need to ensure the switch and asset references become consistent.

Do not diagnose a Rails routing problem until you have compared the fingerprint in the browser’s request with the filename actually present below the alias target.

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

Keep private files out of a public alias

An alias in a publicly reachable location does not perform Rails authorization. Anyone who can construct a matching URL can request a readable file. That design is appropriate for public CSS, JavaScript, fonts, and images, but not for invoices, exports, user uploads, or other resources whose access depends on the signed-in user.

For protected downloads, let Rails authenticate and authorize the request, then use NGINX’s internal file-transfer mechanism. Rails documents this setting:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

In this pattern, Rails decides whether the requester may receive the file and responds with an X-Accel-Redirect instruction. NGINX performs the file transfer from an internal location that is not directly available to the public URL space. Remove any unrestricted public alias to the same directory; otherwise a user could bypass the authorization endpoint by guessing the internal path’s public equivalent.

Validate the setup in a controlled sequence

  1. Check the generated URL. Load the page or inspect its HTML and copy the complete fingerprinted asset URL. Confirm that it starts with the location prefix you configured, normally /assets/.
  2. Check the target file. On the server, verify that the exact filename exists below the alias directory in the active release. A different digest, extension, or capitalization is a different path.
  3. Check directory access. Verify that the NGINX worker can traverse each parent directory and read the file. Permission failures can appear as missing-file responses from the client.
  4. Check slash pairing. A directory-style location and its alias should both end in / in the common /assets/ arrangement. Correct a missing or mismatched slash before changing Rails code.
  5. Check precedence. Review the complete server configuration for regex locations or another prefix that may be handling the request. The most obvious block in an included file is not necessarily the effective one.
  6. Test the configuration. Run:
nginx -t
  1. Reload after a successful test. Then request the asset again and inspect the NGINX access and error logs. The error log commonly reveals the filesystem path NGINX attempted to open, which distinguishes a bad mapping from a missing file or permission problem.
  2. Separate public and private failures. If the file requires authorization, stop debugging the public alias and move the request to the Rails authorization and X-Accel-Redirect design.

Troubleshoot the common 404 and routing symptoms

Symptom Likely cause What to inspect
Every Rails asset returns 404, while the application itself loads. The alias points to an empty, old, or incorrect release directory, or precompilation was skipped. Run the production precompile command, then compare the exact fingerprinted filename with the active alias target.
Only some assets return 404 after a deployment. HTML and static files came from different releases, or an old digest is still being requested. Check which release serves the page and which release the alias resolves to; inspect the requested digest.
NGINX logs show a path containing an unexpected assets/assets segment. root and alias semantics were mixed, or the configured location and target do not reflect the intended mapping. Recalculate the path using the table above. Use root /srv/myapp/current/public for mirrored paths or alias /srv/myapp/current/public/assets/ for replacement.
The browser receives a Rails response instead of a static file. A catch-all or regular-expression location took precedence over the intended asset block. Review location matching and the full included configuration.
Known files still fail after the path is corrected. The NGINX worker cannot traverse a parent directory or read the file. Inspect permissions on every parent directory and the file itself.
Private files are downloadable by changing the URL. A protected directory was exposed with a public alias. Remove the unrestricted location and use Rails authorization with X-Accel-Redirect.

Cache and security decisions

Long-lived caching is a property of the URL scheme as much as of the header. Rails’ fingerprinted asset names let you cache a file for a year because a content change creates a different URL. If you serve files whose names remain constant, use a shorter policy or an explicit invalidation strategy instead of copying the one-year example indiscriminately.

Scope the alias to files intended for public delivery. A Rails release contains configuration, source, and operational files in addition to public/assets; exposing the release root creates an avoidable disclosure risk. The same principle applies to shared upload directories: map only the public subset, and keep authorization-protected files behind Rails.

A practical decision sequence

  1. Identify the browser-visible prefix, such as /assets/, and the directory that should contain the requested file.
  2. If the directory is exactly the URI hierarchy beneath one document root, configure root.
  3. If the URI prefix must be replaced by a differently named or separately located directory, configure alias and pair the trailing slashes.
  4. Precompile Rails assets in the release that will serve the application and verify the fingerprinted output beneath that directory.
  5. Use a narrowly scoped static location and leave dynamic routes in the Rails proxy location.
  6. Add try_files when an explicit existence check or final 404 is preferable to passing missing files to Rails.
  7. Keep protected files out of public aliases and use Rails authorization with X-Accel-Redirect.
  8. Test with nginx -t, reload, request the exact URL, and use access and error logs to verify both the selected location and filesystem path.

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.

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

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

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