在这种情况下,我所做的是限制基于子域或没有子域的路由。在这种情况下,您可以轻松地拥有仅适用于子域的路由,如果有人尝试在没有子域的情况下访问同一路由,则会导致路由错误 (404)。
例如:
路线.rb
Backend::Application.routes.draw do
constraints AppDomainRoutes.new do
# signup paths
get "/signup" => "accounts#new", as: "signup"
post "/signup" => "accounts#create", as: "signup"
# root
root to: "accounts#new"
end
constraints AccountDomainRoutes.new do
# password reset paths
get "/reset_password/:password_reset_token" => "reset_passwords#edit", as: "reset_user_password"
put "/reset_password/:password_reset_token" => "reset_passwords#update", as: "reset_user_password"
# websites
resources :websites
# root
root to: "websites#new"
end
# request password reset paths
get "/reset_password" => "reset_passwords#new", as: "reset_password_request"
post "/reset_password" => "reset_passwords#create", as: "reset_password_request"
# login paths
get "/login" => "sessions#new", as: "login"
post "/login" => "sessions#create", as: "login"
# logout paths
get "/logout" => "sessions#destroy", as: "logout"
delete "/logout" => "sessions#destroy", as: "logout"
end
然后在 lib/routes 中:
app_domain_routes.rb
class AppDomainRoutes
def matches?(request)
request.subdomain.blank? || request.subdomain == "www"
end
end
account_domain_routes.rb
class AccountDomainRoutes
def matches?(request)
request.subdomain.present? && request.subdomain != "www"
end
end
现在,/signup
只能从主应用程序域www.mydomain.com 或 mydomain.com访问,并且/websites/new
只能从*.mydomain.com访问。但是/login
为了方便起见,在这两种情况下仍然可以访问。
显然这并不能解决实际上不是数据库中的帐户invalid.mydomain.com
时访问的问题。invalid
为此,您返回并在application_controller.rb
那里处理重定向,如下所示:
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :redirect_unknown_account
private
# returns current subdomain (account.subdomain) or nil
def account_subdomain
@account_subdomain ||= request.subdomain if request.subdomain.present? && request.subdomain != "www"
end
def current_account
@current_account ||= Account.find_by_username(account_subdomain) if account_subdomain
end
def redirect_unknown_account
if account_subdomain && ! current_account
redirect_to signup_url(host: app_domain), alert: "This account does not exist."
end
end
def account_domain
@account_domain ||= "#{current_account.username}.#{app_domain}" if current_account
end
def app_domain
@app_domain ||= "mydomain.com"
end
end