Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

How to Change Nginx Routing for a Rails App on Ubuntu

A practical Ubuntu guide to changing Nginx routing for Rails, including location precedence, static assets, Puma or Unicorn proxying, proxy_pass trailing-slash behavior, subdirectory deployments, safe reloads, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To change routing for a Rails app on Ubuntu, edit the Nginx server block that owns the app’s hostname. Set Rails’ public directory as the static root, use try_files so existing assets are served directly, and proxy requests that do not match a file to Puma, Unicorn, or another Rails application server. Test the configuration with sudo nginx -t, reload Nginx, and verify both the incoming path and the URI received by Rails.

The detail that causes most routing failures is the URI on proxy_pass. A proxy URL with a URI replaces the portion matched by the location; a proxy URL without a URI generally preserves the original request URI. Choose that behavior deliberately, especially when Rails is mounted below a prefix such as /blog/.

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.

What you are changing

Nginx is the public HTTP entry point, while Rails normally runs behind an application server such as Puma or Unicorn. Nginx receives the request, chooses one location inside the matching virtual host, serves files that already exist in Rails’ public directory, and forwards the remaining requests to the application server.

A reliable Rails arrangement separates those jobs:

  • The server block selects the hostname and listening port.
  • The root directive points to the deployed Rails release’s public directory.
  • The ordinary location / checks for a file or directory with try_files.
  • A named location proxies misses to an upstream Rails listener.
  • Forwarded headers preserve the host, client chain, and HTTPS state Rails needs when constructing URLs and handling redirects.

Changing the route therefore means changing the active virtual-host configuration, not the Rails controller routes. Rails still decides whether an application URL exists after Nginx has selected the backend.

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

Find the active Nginx configuration on Ubuntu

Ubuntu packages commonly use /etc/nginx, but the authoritative location is the path compiled into the installed binary. Check it before editing:

nginx -V

In the command’s output, find the --conf-path value. That file normally includes the site or server definitions used by the running instance. Identify the server block whose server_name matches the Rails hostname you are changing. Edit that block and leave unrelated virtual hosts untouched.

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

Do not assume that the first file you find is active. A hostname can have several server blocks, and an included file can override expectations. Confirm that the block contains the intended listen, server_name, and current application root before changing its locations.

Use a routing layout that serves Rails assets first

The following configuration is the documented pattern to adapt. It listens on port 80, serves files from the Rails public directory, and sends misses to an upstream application server on port 3000.

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.
upstream rails_app {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name example.com;

    root /srv/myapp/current/public;

    location / {
        try_files $uri $uri/ @rails;
    }

    location @rails {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
        proxy_pass http://rails_app;
    }
}

Replace example.com, /srv/myapp/current/public, and the upstream address with the values used by your deployment. The upstream can point at the local TCP listener used by Puma, Unicorn, or another HTTP application server. Your application server must already be listening at that address; Nginx does not start it.

Why the public root matters

Rails places compiled assets and other publicly served files under public. With the root set to the current release’s public directory, a request such as /assets/application.css can be answered by Nginx without waking Rails. The same rule covers files and directories that genuinely exist there.

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

How try_files divides the work

try_files $uri $uri/ @rails; checks the requested path and then its directory form. If neither exists, Nginx internally selects the named @rails location. This prevents ordinary asset and public-file requests from becoming backend requests while allowing Rails to handle dynamic routes, authentication, and application-generated responses.

Understand Nginx location selection before editing routes

Nginx first evaluates prefix locations and remembers the longest matching prefix, then applies its documented regular-expression selection rules. That means a more specific prefix can take precedence over a broad location /. A regular expression should be used only when the route really depends on a pattern; ordinary application prefixes are easier to reason about as prefix locations.

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

When reviewing a routing change, classify the rule you are editing:

Scope Typical form Use it for
Host-level server block server_name example.com; Separating one hostname or deployment from another
Ordinary prefix location /blog/ { ... } Routing every request under a known path prefix
Exact match location = /health { ... } One precise URI that should not fall through to a broader rule
Regular expression location ~ ... { ... } Pattern-based cases that cannot be expressed as a fixed prefix

Before changing a rule, ask which other locations could match the same request. A new prefix can intercept traffic that previously reached location /; a regex can alter the result for a path you thought was covered by a prefix. Test a representative URL for each overlapping rule after reloading.

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.

Choose the correct proxy_pass URI behavior

The presence or absence of a URI in proxy_pass changes what Rails receives. Nginx’s reverse-proxy behavior is easiest to see in a table.

Location Proxy target Request URI sent upstream Use when
location /blog/ proxy_pass http://rails_app/; /blog/posts/42 /posts/42 Rails is mounted at the backend root and should not receive /blog/
location /blog/ proxy_pass http://rails_app; /blog/posts/42 Generally /blog/posts/42 Rails is configured to recognize the /blog/ prefix
location / proxy_pass http://rails_app; /users/sign_in Generally /users/sign_in Sending the complete public URI to Rails

When a URI is specified along with the proxy address, Nginx replaces the part of the request URI that matched the location. In the first row, the trailing slash in http://rails_app/ is significant: it replaces /blog/ with /. Without a URI after the upstream name, the original request URI is generally retained.

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.

Mounting Rails below a subdirectory

If the application is intentionally deployed below a prefix such as /blog/, the Nginx location and Rails must agree about that prefix. Configure Rails with the RAILS_RELATIVE_URL_ROOT environment variable, then choose the proxy_pass form that sends the path Rails expects. A mismatch produces symptoms such as routes that work at the root but fail under the prefix, redirects that drop or duplicate /blog, and asset URLs pointing to the wrong location.

Do not fix a subpath problem by adding or removing a slash at random. Write down one request, the location that should match it, and the exact URI Rails should receive; then make the location and proxy target produce that result.

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.

Configure forwarded request context for Rails

The example sets three headers in the named application location:

  • Host $http_host forwards the host supplied by the client, including the port when it is present.
  • X-Forwarded-For $proxy_add_x_forwarded_for preserves the client address chain as the request passes through proxies.
  • X-Forwarded-Proto $scheme tells Rails whether the public request arrived over HTTP or HTTPS.

proxy_redirect off; prevents Nginx from rewriting the application’s redirect headers automatically. This is useful when Rails is responsible for generating URLs that reflect its configured host and relative URL root. If you change the public prefix or TLS termination arrangement, verify redirects explicitly rather than assuming the old behavior still applies.

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

Change the configuration safely

  1. Record the current behavior. Request the home page, a known asset, a normal Rails route, a deliberately missing route, and every prefixed path affected by the change. Save the status code, redirect target, and visible URL.
  2. Locate the owning server block. Use nginx -V to confirm the configuration path, then edit only the virtual host whose server_name owns the hostname.
  3. Set the Rails public root. Point root at the deployed release’s public directory, not the project parent directory.
  4. Define or update the upstream. Set the address to the Puma, Unicorn, or other HTTP listener that is actually serving this Rails release.
  5. Add the static-file fallback. Put try_files $uri $uri/ @rails; in the broad application location so existing files are handled before dynamic routing.
  6. Configure the named proxy location. Add the forwarded headers, proxy_redirect off, and a deliberate proxy_pass form. Decide whether Rails should receive the original path or a path with the matched prefix removed.
  7. Check syntax before applying. Run:
sudo nginx -t

Do not reload if this test reports an error. Correct the filename, directive, brace, or upstream problem first. A successful syntax test confirms that Nginx can parse the configuration; it does not prove that the backend is reachable or that URI semantics are what you intended.

  1. Reload without stopping the service. Apply the valid configuration with:
sudo systemctl reload nginx

Use the equivalent Nginx reload signal if your installation is managed differently. A reload applies the new worker configuration while avoiding an unnecessary service stop.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Repeat the representative requests. Check the home page, a real asset, a Rails route, a missing route, and each changed prefix. Compare status codes and redirect locations with the baseline.
  2. Inspect both sides of the proxy. Review Nginx access and error logs together with the Rails application-server logs. Confirm which location handled the request, whether a file was found, whether the upstream connected, and which URI Rails processed.

Verify each routing case

Test Expected path What a failure suggests
Home page / reaches Rails Wrong server block, root, upstream, or application listener
Known asset Served from public without a Rails route Incorrect root, missing file, or broken try_files
Dynamic route Rails returns the expected response Upstream address, headers, or proxy URI is wrong
Missing route Rails produces its normal not-found response Request may be intercepted by another location or static fallback
Prefixed route Rails receives the planned prefixed or stripped URI Trailing-slash or RAILS_RELATIVE_URL_ROOT mismatch

Troubleshoot common routing failures

The new rule has no effect

  • Confirm you edited the server block selected by the request’s hostname, not an inactive or unrelated virtual host.
  • Run sudo nginx -t and then reload; editing a file alone does not change running workers.
  • Check for a longer prefix or a regular-expression location that wins for the URL you are testing.
  • Repeat the request with the exact hostname and port used by the client.

Assets return 404 while Rails pages work

  • Verify that the root ends in the deployed app’s public directory.
  • Check that the requested file exists in that release’s public tree.
  • Ensure the broad location still contains try_files $uri $uri/ @rails;.
  • Review the Nginx error log for the filesystem path it attempted.

Rails receives the wrong path

  • Compare the location prefix with the URI portion, if any, on proxy_pass.
  • For a mounted app, test both the trailing-slash form and the no-URI form on paper before editing.
  • Check RAILS_RELATIVE_URL_ROOT when Rails is meant to operate below a subdirectory.
  • Use an application log or request diagnostic to confirm the URI Rails actually saw.

The proxy returns a gateway error

  • Confirm Puma, Unicorn, or the selected application server is running and listening on the configured address.
  • Compare the upstream address in Nginx with the listener address used by the Rails service.
  • Read the Nginx error log for connection-refused, timeout, or name-resolution details.
  • After correcting the backend target, run sudo nginx -t and reload again.

Redirects lose HTTPS or the public prefix

  • Check that X-Forwarded-Proto $scheme is present in the proxy location.
  • Confirm the Host header is forwarded as expected.
  • For a subdirectory deployment, make Rails’ RAILS_RELATIVE_URL_ROOT agree with the URI Nginx sends.
  • Inspect the Location response header to determine whether Rails or Nginx generated the unexpected target.

Decide what to compare before a routing change

Two configurations can both appear to proxy Rails while behaving very differently. Evaluate the change against these dimensions:

Decision Question to answer
Scope Is this a host-wide change, an ordinary prefix, an exact URI, or a pattern rule?
Static handling Should an existing file come directly from public, or should every request reach Rails?
URI behavior Should the backend receive the incoming path unchanged, or should Nginx replace the matched prefix?
Backend target Is the listener a local port, Unix socket, or upstream group, and is it serving the intended release?
Forwarded context Will Rails receive the correct host, client chain, and public scheme?
Operations Have you run the syntax test, reloaded Nginx, checked logs, and exercised representative URLs?

Final verification checklist

  • The edited server block owns the requested hostname.
  • The root points to the Rails release’s public directory.
  • The upstream address matches the running Puma, Unicorn, or other application-server listener.
  • try_files serves existing files before invoking Rails.
  • The selected proxy_pass form produces the intended backend URI.
  • RAILS_RELATIVE_URL_ROOT is set when the app is mounted below a subdirectory.
  • Host, client-address, and scheme headers are forwarded.
  • sudo nginx -t succeeds before the reload.
  • sudo systemctl reload nginx has been run after the valid edit.
  • Home, asset, dynamic, missing, and prefixed URLs have been tested and their logs reviewed.

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 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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

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

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