Skip to content
RailsDev.io

How to Supercharge Your Rails Application with NGINX Reverse Proxy and Load Balancing

Learn step‑by‑step how to configure NGINX as a reverse proxy and load balancer for Ruby on Rails, improving performance, security, and scalability for your SaaS

Diagram: Client → NGINX → Rails → DB
On this page
  1. What is an NGINX reverse proxy and why use it for Rails?
  2. How does an nginx rails deployment improve performance?
  3. Which load‑balancing strategy should I pick for my Rails fleet?
  4. How to configure SSL termination and security headers in NGINX for Rails?
  5. Can I add caching and rate limiting without touching Rails code?
  6. Step‑by‑step: Setting up NGINX as a reverse proxy for a Rails app
  7. How does NGINX affect Rails logging and error handling?
  8. Should I use a single NGINX instance or multiple layers?
  9. What about zero‑downtime deployments with NGINX?
  10. How to monitor cache hit ratio and adjust TTLs?
  11. Frequently asked questions
  12. Conclusion

In an nginx rails deployment, NGINX sits in front of your Rails server, handling all incoming HTTP(S) traffic, terminating TLS, balancing load, and caching static assets—all without changing a single line of Ruby code. By offloading these responsibilities to a high‑performance reverse proxy, you instantly boost response times, harden security, and lay the groundwork for horizontal scaling.

What is an NGINX reverse proxy and why use it for Rails?

A reverse proxy receives client requests, forwards them to one or more backend servers, and returns the backend’s response to the client. For a Rails app, NGINX becomes that front‑line gateway, shielding Puma/Unicorn from direct internet exposure. This separation lets you tune networking, TLS, and caching independently of the Rails process, which stays focused on business logic. The architecture also simplifies zero‑downtime deploys because you can spin up new Rails workers behind the same proxy and let NGINX gracefully drain old connections.

How does an nginx rails deployment improve performance?

NGINX excels at serving static files, handling keep‑alive connections, and multiplexing many sockets with a small worker pool. When it terminates TLS, the CPU‑intensive cryptographic work happens outside the Rails workers, freeing them to process Ruby code faster. Additionally, NGINX can cache responses for assets or even whole pages, reducing the number of Rails requests per second. The net effect is lower latency, higher throughput, and a smaller memory footprint for your Ruby processes.

Which load‑balancing strategy should I pick for my Rails fleet?

The best strategy depends on traffic patterns and server heterogeneity.

Strategy How it works When it shines
Round‑robin Distributes requests sequentially across all upstreams Uniform servers, predictable traffic
Least‑connections Sends traffic to the backend with the fewest active connections Variable request duration, mixed workloads
IP‑hash Routes based on client IP, providing session affinity Simple sticky sessions without Rails‑level cookies

If all your Rails workers are identical and you expect steady traffic, round‑robin is simplest. For APIs with wildly varying request times, least‑connections usually yields better utilization. I often start with round‑robin and switch to least‑connections after monitoring connection counts for a short period.

How to configure SSL termination and security headers in NGINX for Rails?

Terminate TLS at the proxy, then forward plain HTTP to Puma on a private network. This reduces latency and lets you reuse the same certificate across multiple services. Add security‑focused headers (e.g., Strict-Transport-Security, X‑Content-Type-Options) directly in the NGINX block so every response inherits them, regardless of Rails configuration.

nginx
server {
    listen ssl http2;
    server_name example.com;

    ssl_certificate     /etc/ssl/certs/example.crt;
    ssl_certificate_key /etc/ssl/private/example.key;
    ssl_protocols       TLSv1 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    # Security headers
    add_header Strict-Transport-Security "max-age=; includeSubDomains; preload" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

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

The proxy_set_header directives ensure Rails sees the original host and protocol, allowing helpers like url_for to generate correct URLs. See the official NGINX SSL guide for more options: https://nginx.org/en/docs/http/ngx_http_ssl_module.html.

Can I add caching and rate limiting without touching Rails code?

Yes. NGINX can cache responses based on status codes, request methods, or custom headers, and it can enforce request‑rate limits per IP or per key. Because caching happens before the request reaches Rails, you avoid any Ruby‑level changes. For rate limiting, you define a shared memory zone that tracks request counts and then apply the limit_req directive to the desired location.

nginx
# Define a shared memory zone for rate limiting
limit_req_zone $binary_remote_addr zone=api_limit: memory rate=r/m;

server {
    ...

    location /api/ {
        limit_req zone=api_limit burst= nodelay;
        proxy_pass http://rails_upstream;
    }

    # Cache GET responses for assets
    location /assets/ {
        proxy_cache my_cache;
        proxy_pass http://rails_upstream;
    }
}

The cache key defaults to the full request URI, which works well for static assets. For API responses you might want to vary by Accept header; that can be expressed with proxy_cache_key "$scheme$request_method$host$request_uri$http_accept".

Step‑by‑step: Setting up NGINX as a reverse proxy for a Rails app

  1. Install NGINX – Use the official package repository for your distro (apt-get install nginx on Ubuntu, yum install nginx on CentOS). Verify the binary includes the needed modules with nginx -V.

  2. Create an upstream block – Define the Rails workers (Puma, Unicorn, or Passenger) that NGINX will forward to. Example:

    nginx
    upstream rails_upstream {
        server 127.0.0.1;
        server 127.0.0.1;
    }
  3. Write the server block – Include SSL termination, security headers, and proxy settings as shown earlier.

  4. Enable caching and rate limiting – Add the proxy_cache_path directive globally, then reference it in location blocks.

  5. Test the configuration – Run nginx -t to catch syntax errors, then reload with systemctl reload nginx.

  6. Verify Rails sees the correct protocol – In a Rails console, check request.protocol or request.ssl?. It should return https because of the X-Forwarded-Proto header.

  7. Monitor – Use nginx_status or tools like Uptime Kuma (see our guide on monitoring) to watch request rates, cache hit ratios, and upstream health.

These steps require zero modifications to your Rails configuration files, proving that performance gains can be achieved purely at the network layer.

How does NGINX affect Rails logging and error handling?

When NGINX proxies a request, any client‑error or server‑error response generated by Rails still passes through NGINX, which can add its own log line. To keep logs coherent, configure NGINX’s access_log format to include the upstream status and response time:

nginx
log_format combined_upstream '$remote_addr - $remote_user [$time_local] '
    '"$request" $status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" $upstream_status $request_time';
access_log /var/log/nginx/access.log combined_upstream;

Rails’ own logs remain unchanged, but you now have a single source that correlates client latency ($request_time) with the Rails response code ($upstream_status). This makes troubleshooting faster, especially when combined with Rails’ built‑in exception notifications.

Should I use a single NGINX instance or multiple layers?

If you run a small SaaS with a handful of servers, a single NGINX host per environment (staging, production) is sufficient. For larger deployments, consider a two‑tier approach: a front‑facing load balancer (e.g., AWS ELB or HAProxy) that distributes traffic to several NGINX reverse proxies, each of which then balances across a pool of Rails workers. This adds redundancy and isolates TLS termination from internal traffic, but also introduces extra latency. The decision hinges on your SLA requirements and budget.

What about zero‑downtime deployments with NGINX?

Because NGINX holds the client‑facing sockets, you can restart or replace Rails workers without dropping connections. The typical pattern is:

  1. Deploy new code and start fresh Puma workers on a new port.
  2. Update the upstream block to include the new server and mark the old one as down (or remove it).
  3. Reload NGINX (nginx -s reload). Existing connections continue on the old workers; new connections flow to the fresh ones.
  4. After all old workers finish their keep‑alive requests, stop them.

Rails’ built‑in hot‑restart feature works hand‑in‑hand with this approach, and you can automate it with Capistrano or Kamal (see our post on Kamal for Rails). This strategy requires no code changes, only orchestration.

How to monitor cache hit ratio and adjust TTLs?

NGINX exposes cache metrics via the stub_status module and the newer cache status module. Enable the status endpoint:

nginx
server {
    listen 127.0.0.1;
    location /nginx_status {
        stub_status;
        allow 127.0.0.1;
        deny all;
    }
}

Query curl http://127.0.0.1/nginx_status and look for cache‑related lines (if you’ve compiled the module). Tools like Grafana can scrape these metrics and display hit/miss percentages. If you see a low hit ratio, consider lengthening proxy_cache_valid for assets that change rarely, or adding proxy_cache_key variations to avoid unnecessary misses.

Verification note: The performance improvements described (e.g., latency reduction, CPU off‑loading) depend on the specific workload, hardware, and network conditions of each deployment. Benchmarks should be measured in your own environment before assuming identical gains.

Frequently asked questions

Does NGINX replace the need for a CDN?

Not entirely. NGINX can cache static assets locally, but a CDN still provides global edge distribution, reducing latency for users far from your data center. Use NGINX for origin caching and let the CDN pull from it.

Can I run NGINX and Rails on the same server?

Yes, especially for small apps or development environments. Just ensure NGINX listens on standard ports and proxies to a Rails server bound to localhost. For production at scale, separating concerns across machines improves fault isolation.

What Ruby version does NGINX care about?

None. NGINX interacts with Rails over HTTP, so the Ruby interpreter version is irrelevant to the proxy. This is why you can upgrade Ruby or Rails without touching NGINX configuration, as long as the endpoint remains reachable.

How do I troubleshoot “Bad Gateway” errors?

A Bad Gateway usually means NGINX couldn’t reach the upstream or the upstream returned an invalid response. Check the NGINX error log (/var/log/nginx/error.log) for messages like “connect() failed” or “upstream timed out”. Verify that the Rails server is listening on the expected port and that firewall rules allow traffic from NGINX.

Is it safe to expose Rails error pages through NGINX?

Never. Configure Rails to render generic error pages in production (config.consider_all_requests_local = false). Additionally, add proxy_intercept_errors on; and define custom error pages in NGINX to hide stack traces from the client.

Does NGINX support HTTP/2 for Rails APIs?

Absolutely. Enable http2 on the listen directive (as shown earlier) and ensure your Rails app responds to HTTP/1.1 as a fallback. Most modern browsers and API clients will negotiate HTTP/2 automatically.

Conclusion

An nginx rails deployment gives you immediate performance, security, and scalability wins without touching a single line of Ruby. By terminating TLS, balancing load, caching assets, and enforcing rate limits at the proxy layer, you free your Rails workers to focus on business logic and keep your codebase clean. If you’re ready to level up your Rails infrastructure, start with the step‑by‑step guide above, monitor the key metrics, and iterate on caching policies. Need hands‑on help or a custom architecture plan? Feel free to book a discovery call or explore our /services/custom-web-application-development offering.

For deeper dives into related topics, check out our posts on Hotwire vs React for Rails Apps and how to improve deployment reliability with OpenSRE /blog/rails-deployment-reliability-opensre.

Primary source: the official project page.

Keep reading