Sobes.tech
Middle

Why install Nginx before Ruby?

sobes.tech AI

Answer from AI

Nginx is installed in front of a Ruby application (such as Rails or Sinatra) for the following reasons:

  1. Serving static files: Nginx efficiently (faster and with less resource consumption) serves static files (CSS, JS, images), freeing Ruby processes to handle dynamic requests.
  2. Reverse proxy: Nginx acts as a reverse proxy, accepting all incoming HTTP requests and forwarding them to Ruby servers (such as Puma, Unicorn) via protocols (e.g., HTTP or Unix Domain Socket). This allows managing multiple Ruby processes and load balancing between them.
  3. SSL/TLS termination: Nginx can handle encrypted SSL/TLS connections, offloading this task from the Ruby application.
  4. Caching: Nginx can cache responses, speeding up the delivery of frequently requested content.
  5. Compression: Nginx can compress responses (gzip, brotli), reducing the volume of transmitted data.
  6. Load balancing: Nginx can distribute incoming requests among multiple Ruby application instances, increasing availability and scalability.
  7. Logging: Nginx provides powerful HTTP request logging capabilities.
  8. Security: Nginx can perform basic security functions, such as rate limiting, IP blocking, and protection against certain types of attacks (e.g., DDoS at the HTTP level).
  9. Separation of concerns: Nginx handles infrastructural tasks (serving HTTP, SSL), allowing the Ruby application to focus on business logic.

Example Nginx configuration for proxying to Unicorn:

server {
    listen 80;
    server_name your_domain.com;

    location / {
        proxy_pass http://unix:/path/to/your/app/tmp/sockets/unicorn.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Optional: serve static assets directly
    location ~* \.(css|js|jpg|jpeg|gif|png|html)$ {
        root /path/to/your/app/public;
        expires 1d;
    }
}