Search code examples
ruby-on-railsubuntunginxunicorn

Why I can't access to subdomain through nginx proxy pass?


I wanna to deploy my Ruby on Rails application in my local computer by Nginx and RoR web servers (like Unicorn, Thin or WEBrick).

As shown below, I wanna access to my web-app by post subdomain:

upstream sub {
  server unix:/tmp/unicorn.subdomain.sock fail_timeout=0;
#  server 127.0.0.1:3000;
}

server {
  listen   80;
  server_name post.subdomain.me;

  access_log /var/www/subdomain/log/access.log;
  error_log  /var/www/subdomain/log/error.log;
  root     /var/www/subdomain;
  index    index.html;

  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  Host $http_host;
    proxy_redirect  off;
    try_files /system/maintenance.html $uri $uri/index.html $uri.html @ruby;
  }

  location @ruby {
    proxy_pass http://sub;
  }
}

Everything is working fine and when I type post.subdomain.me I can see my RoR app.

Problem: When I use post.subdomain.me url I can't access to my subdomain (request.subdomain returns empty and request.host returns subdomain instaed of subdomain.me). But when I use post.subdomain.me:3000 every things work perfect (I lost half of my hairs to realize that). Why and How can I resolve it?


Solution

  • When you access app with port - you are accessing the rails server directly, not proxied by nginx, this is fine for debug, but usually is not well for production.

    Probably host header is not passed over by client, $host defaults to nginx host

    Try

    location @ruby {
        proxy_set_header Host $host;
        proxy_pass http://sub;
    }
    

    And a 'hardcode'-way: proxy_set_header Host post.subdomain.me;