Rails 在 Rails 裡實作 Custom Domain 與 Subdomain

xdite · 2013年07月21日 · 最后由 xdite 回复于 2013年07月23日 · 3969 次阅读
本帖已被设为精华帖!

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;
  .....
}
共收到 10 条回复

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.

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册