VisezTrance

  • December 13, 2008 5:32 PM

    Dynamic subdomains with Nginx

    By Daniel
    I had to implement dynamic subdomains for a large Ruby On Rails application we had been developing. While the most straightforward way of doing this is to code the functionality within your application, I decided on trying a different approach by doing everything server side.
    For example, each time I access http://daniel.myapp.com, this would send a request to the rails instance that may look like http://myapp.com/profiles/daniel. On the other hand other static resources such as stylesheets and images, must still point to their original locations.
    On Nginx my code resembled this:

    location / {
      set $subdomain "";
      set $subdomain_root "";
      set $doit "";
      if ($host ~* "^(.+)\.myapp\.com$") {
        set $subdomain $1;
        set $subdomain_root "/profiles/$subdomain";
        set $doit TR;
      }
      if (!-f $request_filename) {
        set $doit "${doit}UE";
      }
      if ($doit = TRUE) {
        rewrite ^(.*)$ $subdomain_root$1;
        break;
      }
      # root ..
      # proxy_set_header ..
      # etc..
    }

    The $doit thing is just a hack meant to allow multiple if conditions on Nginx.

    Tags:

    • nginx,
    • subdomains
  • Monthly Archives

    • October 2013 (2)
    • May 2012 (1)
    • October 2011 (1)
    • September 2011 (2)
    • March 2011 (3)
    • February 2011 (1)
    • January 2011 (1)
    • September 2010 (1)
    • August 2010 (1)
    • June 2010 (1)
    • April 2010 (1)
    • December 2009 (1)
    • October 2009 (1)
    • September 2009 (1)
    • August 2009 (1)
    • July 2009 (2)
    • April 2009 (2)
    • February 2009 (1)
    • January 2009 (2)
    • December 2008 (1)
    • October 2008 (1)
  • Pages

    • About / Contact

2008, © Daniel Mircea