Blog.XDite.net

Ruby / Rails / Web Development
  • 課程
  • About Me
  • Archive
  • feeds
  • Rails
  • Startup
  • Growth
  • Agile
  • Career
  • 開課列表

Posts match “ subdomain ” tag:

over 12 years ago

Implement Subdomain & Custom Domain in Rails

We recently launch subdomain & custom domain features in our product: Logdown, a Markdown Blogging Platform.

People keep asking me how to implement, here is how :

(1) Constraint Routing

config/routes.rb
  constraints(Subdomain) do
    get '/' => 'posts#index'
    
   
    resources :posts do
      collection do
        get :search
      end
    end
  end 

And in Subdomain class:

If it doesn't match logdown.com & www.logdown.com, then it goes straight to the constraint routing.

lib/subdomain.rb
class Subdomain
  def self.matches?(request)

    case request.host
    when Setting.host, "www.#{Setting.host}", nil
      false
    else
      true
    end  
  end

end

(2) Find Current Blog

In PostsController, we also build a method find_blog to find @current_blog.

The sequences will be : subdomain => custom domain => Not Found

app/controller/posts_controller.rb
class PostsController < ApplicationController

  before_filter :find_blog
  
  def find_blog
    case request.host
    when "www.#{Setting.host}", Setting.host, nil
    else     
      if request.host.index(Setting.host)
        @current_blog = Blog.find_by_subdomain(request.host.split('.').first)
      else
        @current_blog = Blog.find_by_fqdn(request.host)
      end

      if !@current_blog
        redirect_to Setting.domain
      end

    end  
  end
  
end

(3) Nginx Setting

/opt/nginx/conf/nginx.conf
    server {
      listen 80 default;
      .....
    }

The code is very simple, but it tooks me lots of time to figure out...

  • rails
  • subdomain
  • routing
  • July 21, 2013 14:05
  • Permalink
  • Comments
 

Copyright © 2016 xdite_cheng . Powered by Logdown.
Based on work at subtlepatterns.com.