Build url without subdomain in rails 3

I am currently detecting if a user has a specific subdomain and redirects the user to a URL without a subdomain as such:

subdom = request.subdomains.first if subdom == "redirectme" redirect_to(request.protocol + request.domain + ":" + request.port.to_s) end 

As you can see, I manually restore the domain so as not to include the subdomain, to replace something like: http://redirectme.example.com{000 to: http://example.com{000

However, I must remember that sometimes there will be no port (and therefore the colon after the domain is redundant), and I suspect there are other things that I did not take into account. What is the best way to get a complete domain without its subdomain component?

Thanks!

+4
source share
3 answers

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

If you want the colon to pass, you can do the following:

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

Just a scratch test that does the magic!

+12
source

What about root_url( :subdomain => false ) ?

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

This will require the port to be explicitly specified 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
source

Source: https://habr.com/ru/post/1348028/


All Articles