设计基于子域的应用程序,当在子域下找不到用户时重定向到默认vhost



构建一个以用户帐户作为子域的设计 Rails 应用程序 当用户访问的子域不存在时,我无法弄清楚如何重定向到默认(default.domain.com)子域。

例如:

  • user.domain.com 工作(用户存在于数据库中)
  • user2.domain.com 失败(用户不在数据库中),应重定向到 default.domain.com

如何做到这一点?我使用以下代码,但基于 Rails.env 的重定向进入了一个永无止境的循环:(

class ApplicationController < ActionController::Base
  protect_from_forgery
  layout "application"
  before_filter :account
  def account
    @user     = User.where(:subdomain => request.subdomain).first || not_found
  end
  def not_found
      # next 2 lines is a temp solution--- >
      raise ActionController::RoutingError.new('User Not Found')
      return
      # --- > this below fails results in endless loop
      if Rails.env == "development"
        redirect_to "http://default.domain.dev:3000"
        return
      else
        redirect_to "http://default.domain.com"
      end
    end
end

不确定会有一种特别好的方法可以做到这一点,并且在没有看到大局的情况下在这里做出正确的判断并不容易,但是,也许您应该将默认域存储为常量,然后在重定向之前检查这一点,以打破循环,就像它一样!

这样的东西会更好;

class ApplicationController < ActionController::Base
  protect_from_forgery
  layout "application"
  before_filter :account
  def account
    @user = User.where(:subdomain => request.subdomain).first
    if @user.nil? and DEFAULT_URL =~ request.subdomain
      port = request.server_port == 80 ? '' : ":#{request.server_port}"
      redirect_to "http://#{DEFAULT_URL}#{port}"
    end
  end
end

您了解了大致的想法,您可以在初始值设定项中设置DEFAULT_URL。

相关内容

最新更新