運営中のサービス「BoxToYou(https://www.box2you.com)」でカスタムサブドメイン機能をリリースしました。
いくつかハマったところがあったので、数回に分けてメモしていきまする。
今回は、routingの設定とリンクの設定方法について。
サブドメインの条件定義
まず、subdomain.rb でサブドメインの条件をかきかき。
#subdomain.rb class Subdomain def self.matches?(request) request.subdomain.present? && request.subdomain != "www" end end
RailsのRequestオブジェクトにsubdomainメソッドが定義されているので、
request.subdomain
という風にリクエストのサブドメイン部分「http://◯◯◯.example.com」の◯◯◯を簡単に呼び出せます。ただし、「www」もサブドメインとして処理されますので、カスタムサブドメインの設定としては不適切として、
request.subdomain != "www"
という風にmatchの条件から排除しています。
ルーティングの設定
次に、routesファイルの設定。
#routes.rb # routes setting of subdomain # should be placed above the "root :to" path require "#{Rails.root}/app/helpers/subdomain" constraints(Subdomain) do match "/" => 'users#show' match "/*a" => 'application#render_error404' end # other routes settings root :to => "users#index" #
上記のsubdomain.rbを読み込み、
constraints で条件がマッチした際には、別のactionに飛ばすようにしています。
match "/" => 'users#show' match "/*a" => 'application#render_error404'
については、アプリの仕様で、root_path の後ろには何も来ない場合の処理です。404 error のページへ飛ぶようにcontroller側で設定しています。
コントローラー側の制御
ちなみに、subdomain の controller 側の処理はこんな感じです。
# users_controller.rb # if no users exist who has the requested.subdomain, # redirect the request to the top page. unless User.where(:subdomain => request.subdomain).present? return redirect_to url_for(:subdomain => false) end # specific a user from request.subdomain @user = User.where(:subdomain => request.subdomain).first
リクエストされたサブドメインを持ったユーザーが存在しなかった場合は、トップページにリダイレクトしています。
url_for(:subdomain => false)に関しては、subdomain_url_helper.rb というヘルパーを作って設定しています。(詳細はこちら)
そして、次に、subdomain は各ユーザーがユニークで持てるようにしているので、
@user = User.where(:subdomain => request.subdomain).first
で特定のユーザーを特定して、インスタンス変数に入れています。
こんな感じで、だいたいの設定はできるかと。
関連記事
参考記事