Rails Restful路由和子域 [英] Rails Restful Routing and Subdomains

查看:70
本文介绍了Rails Restful路由和子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何插件或方法可以转换资源路由,从而将控制器名称放置为子域。

I wondered if there were any plugins or methods which allow me to convert resource routes which allow me to place the controller name as a subdomain.

示例:

map.resources :users
map.resource :account
map.resources :blog
...

example.com/users/mark
example.com/account
example.com/blog/subject
example.com/blog/subject/edit
...

#becomes

users.example.com/mark
account.example.com
blog.example.com/subject
blog.example.com/subject/edit
...

我意识到我可以使用命名的路由来做到这一点,但想知道是否有某种方法可以保留我当前简洁的route.rb文件。

I realise I can do this with named routes but wondered if there were some way to keep my currently succinct routes.rb file.

推荐答案

<最好的方法是编写一个简单的机架中间件库,该库重写请求标头,以便您的rails应用获取您期望的url,但是从用户的角度来看,URL不会改变。这样,您不必对Rails应用程序(或路由文件)进行任何更改

The best way to do it is to write a simple rack middleware library that rewrites the request headers so that your rails app gets the url you expect but from the user's point of view the url doesn't change. This way you don't have to make any changes to your rails app (or the routes file)

例如,机架库将重写:users.example.com = > example.com/users

For example the rack lib would rewrite: users.example.com => example.com/users

此gem应该为您完全做到这一点: http://github.com/jtrupiano/rack-rewrite

This gem should do exactly that for you: http://github.com/jtrupiano/rack-rewrite

使用代码示例更新

注意:这是快速编写的,完全未经测试,但是应该使您走上正确的道路。另外,我还没有检查过机架重写的gem,这可能会使它更简单

Note: this is quickly written, totally untested, but should set you on the right path. Also, I haven't checked out the rack-rewrite gem, which might make this even simpler

# your rack middleware lib.  stick this in you lib dir
class RewriteSubdomainToPath

  def initialize(app)
    @app = app
  end

  def call(env)
    original_host = env['SERVER_NAME']
    subdomain = get_subdomain(original_host)
    if subdomain
      new_host = get_domain(original_host)
      env['PATH_INFO'] = [subdomain, env['PATH_INFO']].join('/')
      env['HTTP_X_FORWARDED_HOST'] = [original_host, new_host].join(', ')
      logger.info("Reroute: mapped #{original_host} => #{new_host}") if defined?(Rails.logger)
    end

    @app.call(env)

  end

  def get_subdomain
    # code to find a subdomain.  simple regex is probably find, but you might need to handle 
    # different TLD lengths for example .co.uk
    # google this, there are lots of examples

  end

  def get_domain
    # get the domain without the subdomain. same comments as above
  end
end

# then in an initializer
Rails.application.config.middleware.use RewriteSubdomainToPath

这篇关于Rails Restful路由和子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆