Rails 在 Rails 裡實作 Custom Domain 與 Subdomain

xdite · July 21, 2013 · Last by xdite replied at July 23, 2013 · 4603 hits
Topic has been selected as the excellent topic by the admin.

http://blog.xdite.net/posts/2013/07/21/implement-subdomain-custom-domain

其實原理很簡單。但是網路上能找到的方式都不太全,所以就決定放了一下我的.... 代碼看起來算簡單,但是組裝起來也花了我接近兩個整天....

(1) Constraint Routing

constraints(Subdomain) do
  get '/' => 'posts#index'

  resources :posts do
    collection do
      get :search
    end
  end
end

And in Subdomain class:

If it doesn't matches logdown.com & www.logdown.com, then it will go straight to the constraint routing.

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

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

server {
  listen 80 default;
  .....
}

ruby china 不支援 octopress syntax ...

@ruby_sky url 沒有這篇裡面講的這麼簡單,很多地雷的....

#4 楼 @xdite 晚上去试试。:)

好东西,现在还用不到,留着以后用

mark 下先

#2 楼 @xdite 介意我纠正一下英文语法不?If it doesn't matches logdown.com & www.logdown.com, then it will go straight to the constraint routing. -> If it doesn't match logdown.com or www.logdown.com, it goes straight to the constraint routing.

You need to Sign in before reply, if you don't have an account, please Sign up first.