Get subdomain(s) in Rack middleware

I have found myself needing to know what, if any, the subdomain is in a request… from within a Rack middleware. I’d like to redirect, change the path, or set the Current.locale based on that subdomain.

To my surprise every time, this doesn’t work.

For: https://en.wikipedia.org

Rack::Request.new(env).subdomain #=> 'en'

It’d be a lot cooler if it did.

Also, if this worked to handle multiple subdomains too.

For: http://del.icio.us

Rack::Request.new(env).subdomains #=> ['del', 'icio']


Thanks for doing this May of WTFs! And for all the hard work that yall do on Rails, in general.

:heart:

2 Likes

@tenderlove do you think there would be unruly perf implications to having a tiny middleware that added this by default?

I am not sure this should be included in Rack or even Rails.

The dependency that handles this correctly is this

We also built a more minimal/leaner implementation for Discourse with

It should be pretty straight forward to include either of these gems for your use case.

Both dependencies are rather big and only a few web apps need the features.

I agree with @samsaffron. I understand why this is useful, but parsing domain names is Not Trivial ™ and would be better handled by an external library. We could figure out a way to add a method to the request object, but I think that would be better handled in the respective library.