over 10 years ago

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...

← Web Startup 適合使用的服務與工具 (2013) Font awesome & Firefox with CloundFront →
 
comments powered by Disqus