Search code examples
ruby-on-railsnginxpuma

How do I handle dynamic subdomains with Nginx + Rails server?


I've got a problem with proxying of subdomain's name from nginx to rails server. In my rails app I have links like tenant1.localhost:3000, tenant2.localhost:3000, etc. and it works fine. On production I use Nginx + Puma and nginx doesn't proxy to puma any request if I open link with subdomain.

nginx.conf

upstream puma_muninn {
  server app:3000;
}

server {

  listen 80;

  client_max_body_size 4G;
  keepalive_timeout 10;

  error_page 500 502 504 /500.html;
  error_page 503 @503;

  server_name localhost puma_muninn;
  server_name ~^(?<subdomain>.+)localhost$;
  root /var/www/muninn/public;
  try_files $uri/index.html $uri @puma_muninn;

  location @puma_muninn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://$subdomain.puma_muninn;
    # limit_req zone=one;
    access_log /var/www/muninn/log/nginx.access.log;
    error_log /var/www/muninn/log/nginx.error.log;
  }

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  location = /50x.html {
    root html;
  }

  location = /404.html {
    root html;
  }

  location @503 {
    error_page 405 = /system/maintenance.html;
    if (-f $document_root/system/maintenance.html) {
      rewrite ^(.*)$ /system/maintenance.html break;
    }
    rewrite ^(.*)$ /503.html break;
  }

  if ($request_method !~ ^(GET|HEAD|PUT|PATCH|POST|DELETE|OPTIONS)$ ){
    return 405;
  }

  if (-f $document_root/system/maintenance.html) {
    return 503;
  }

  location ~ \.(php|html)$ {
    return 405;
  }
}

production.rb

config.action_dispatch.tld_length = 2

But as I said puma doesn't even get requests from nginx.

Any ideas?


Solution

  • A domain in nginx.conf has to be specific instead of localhost.