1
votes

I have a rails app which is deployed over Capistrano to a VPS with a very similar setup to this Railscast. I have both mydomain.co.uk and admin.mydomain.co.uk. The subdomains work fine locally using lvh.me and the standard Webbrick server, but in production admin.mydomain.co.uk shows exactly the same content as mydomain.co.uk.

My routes.rb file:

class AdminDomain
  def self.matches?(request)
    puts "Sub = #{request.subdomain}"
    request.subdomain.present? && request.subdomain == "admin"
  end
end

MyApp::Application.routes.draw do

  constraints(AdminDomain) do
    scope :module => "admin" do
      match '', to: 'admin#index'

      resources :users
    end
  end

  # All the mydomain.co.uk routes...

My Nginx config:

upstream unicorn {
  server unix:/tmp/unicorn.<%= application %>.sock fail_timeout=0;
}

server {
  listen 80;
  root <%= current_path %>/public;

  server_name mydomain.co.uk admin.mydomain.co.uk;

  listen 443 ssl;
  ssl_certificate /home/deployer/mydomain_combined.crt;
  ssl_certificate_key /home/deployer/mydomain.key;
  proxy_set_header X-Forwarded-Proto $scheme;

  auth_basic            "Restricted";
  auth_basic_user_file  htpasswd;

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

  location = /favicon.ico {
    expires    max;
    add_header Cache-Control public;
  }

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

  error_page 503 @maintenance;

  location @maintenance {
    rewrite  ^(.*)$  /system/maintenance.html last;
    break;
  }

  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  client_max_body_size 4G;
  keepalive_timeout 10;
}

The only idea I have is that Nginx is not passing on the request url to the unicorn. I had a similar issue with SSL but solved that by adding proxy_set_header X-Forwarded-Proto $scheme;. How can I get the subdomains to function correctly in a production environment under Nginx and Unicorn?

1
I also had this problem and I post about it. Here's a answer: stackoverflow.com/questions/18134046/…user547202

1 Answers

2
votes

It seems that under my setup in production request.subdomain was set to 'admin.mydomain' whereas in development it was just 'admin'.

Therefore adding this into the routes.rb with a regex works both locally and on my production server:

constraints :subdomain => /admin.*/ do
  scope :module => "admin" do
    root to: 'admin#index'
  end
end