Support for multiple domains/subdomains in Rails

2020-06-06 04:43发布

I have a Rails app that has a similar setup to Tumblr, that is, you can have either: (1) Subdomain hosting (your-username.myapp.com) (2) Domain hosting (your-username.com)

Both would forward to a personalized website for that user, created with my application.

How can I accomplish this in Rails? I have been able to get (1) working with subdomain-fu, but I'm not sure how to get (2) working. Any pointers (plugins, gems, tutorials), etc. would be greatly helpful, I can't seem to find any.

Thanks!

2条回答
Rolldiameter
2楼-- · 2020-06-06 05:02

The principle for domains is the same as the subdomain - find the domain, map to an account.

The details will depend on how your hosting is going to handle the DNS.

I am currently using Heroku and its wildcard service. In this case, the domain is mapped with a cname to the subdomain hosted by my Heroku app. From here I can work out the associated account and details.

查看更多
闹够了就滚
3楼-- · 2020-06-06 05:17

EDIT: I've found a much easier way: http://www.arctickiwi.com/blog/7-host-and-domain-based-routing-in-ruby-on-rails

Not exactly an answer but this is the best I can give. Maybe this'll help you too.

Ideally, this blog post from transfs.com and subdomain-fu should do the trick. I've been trying to implement it, however, and they don't seem to play nicely together.

Basically, if I don't include the intiializer, the subdomain route works fine. If I include the initializer, the subdomain route breaks (everything gets caught by map.root). I have a feeling it's with the way it builds the condition string in the initializer. If you can figure out how it breaks, then you'll have a working app.

My initializer:

module ActionController
  module Routing
    class RouteSet
      def extract_request_environment(request)
        env = { :method => request.method }
        env[:domain] = request.domain if request.domain
        env[:host] = request.host if request.host
env end end class Route alias_method :old_recognition_conditions, :recognition_conditions def recognition_conditions result = old_recognition_conditions [:host, :domain].each do |key| if conditions[key] operator = "===" if conditions[key].is_a?(Regexp) operator = "=~" end result << "conditions[:#{key.to_s}] #{operator} env[:#{key.to_s}]" end end result end end# end class Route end end

My routes (just for development). You'll see my local development domain, stiltify.dev. Sorry, I tried to make it look good in here but I couldn't get the code block to look nice. I put it on pastie instead: http://pastie.org/940619.

The comments section in Ryan Bates' screencast was very helpful, and got me to figure out the subdomain => false and the other errors they were getting into. Still didn't fix the problem though!

查看更多
登录 后发表回答