LoginSignup
15
16

More than 5 years have passed since last update.

Rails 3 でサブドメインを使う場合のルーティング設定

Last updated at Posted at 2013-06-16

ルーティングで api ドメイン以下だけで使用できるコントローラや Rack middleware を設定したいという場合について考えたいと思います。

サブドメインからだけアクセスできるようにする

以下のようなクラスを定義します。

config/routes.rb
class UseSubdomain
  def initialize(domain)
    @domain = domain
  end

  def matches?(request)
    request.subdomain.present? && request.subdomain == @domain
  end
end

以下のようにして使用します。

config/routes.rb
Test::Application.routes.draw do
  constraints(UseSubdomain.new('api')) do
    mount Test::Api => '/'
  end

  constraints(UseSubdomain.new('dashboard')) do
    root to: 'dashboard#index'
  end
end

ネイキッド / www ドメインからだけアクセスできるようにする

上記のままではネイキッドドメイン/www ドメインでアクセスしたい部分でもサブドメインでアクセスすることを許容してしまいますので、さらに以下のクラスを定義し、制限を行います。

config/routes.rb
class OmitSubdomain
  def matches?(request)
    request.subdomain.blank? || request.subdomain == 'www'
  end
end

この使用方法は以下のようになります。

config/routes.rb
Test::Application.routes.draw do
  constraints(OmitSubdomain.new) do
    resources :articles
    root to: 'site#index'
  end
end
15
16
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16