Rails: how to get the current host, or build a URL with it?

HappyDeveloper picture HappyDeveloper · Feb 26, 2012 · Viewed 59.5k times · Source

I need to use the host to build a URL with a different port.

For example, if the host is example.com, I need to generate a URL like http://example.com:8080/

I need it to be portable, so when I'm in my local enviroment it shows http://localhost:8080/ instead.

Any ideas?

Answer

Alex D picture Alex D · Feb 26, 2012

I often use a before_filter in ApplicationController to set an instance variable with the host name, something like this:

@hostname = request.host || "www.mydomain.com"

You can also use request.port to get the port number which the request came through (taken from the HTTP headers).