http://blog.xdite.net/posts/2013/07/21/implement-subdomain-custom-domain
其實原理很簡單。但是網路上能找到的方式都不太全,所以就決定放了一下我的.... 代碼看起來算簡單,但是組裝起來也花了我接近兩個整天....
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
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
server {
listen 80 default;
.....
}