开发者

construct url without subdomain in rails 3

I'm currently detecting whether a user has a certain subdomain and redirecting the user to the url without the subdomain as such:

subdom = req开发者_运维知识库uest.subdomains.first
if subdom == "redirectme"
  redirect_to(request.protocol + request.domain + ":" + request.port.to_s)
end

As you can see, I'm reconstructing the domain manually to not include the subdomain to replace something like: http://redirectme.example.com:3000 to: http://example.com:3000

However, I have to keep in mind that sometimes there won't be a port (and so the colon after the domain is redundant) and I suspect there are other things I didn't account for. What's a better way of getting the full domain without its subdomain component?

Thanks!


How about root_url( :subdomain => false )?


Actually i don't know if there are better ways. As for the components, you pretty much got it: protocol, domain and port.

If you want the colon gone, you can do like this:

redirect_to(request.protocol + request.domain + (request.port.nil? ? '' : ":#{request.port}"))

Just a nil check that performs the magic!


redirect_to URI.parse(request.uri).tap { |uri| uri.host = request.domain }.to_s

It will take care if port should be explicitly present or not in the URI.

Examples:

URI.parse("http://www.example.com/").to_s #"http://www.example.com/"
URI.parse("http://www.example.com:80/").to_s #"http://www.example.com/"
URI.parse("https://www.example.com:443/").to_s #"https://www.example.com/"
URI.parse("http://www.example.com:3000/").to_s #"http://www.example.com:3000/"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜