How to Get the Current Absolute URL in Rails

1 min read

Every Rails controller includes two accessor methods pointing to the request and the response objects associated with the current HTTP request cycle. The request method returns an instance of the ActionDispatch::Request class, which wraps the HTTP request and provides a nice API to inspect the request.

Use original_url method on the request object to get the current absolute URL.

# Returns the original request URL as a `String`

# get "/articles?page=2"

request.original_url # => ""

Here's the source code for this method.

def original_url
  base_url + original_fullpath

The base_url returns the URL containing the protocol and the domain, and the original_fullpath returns a String with the requested path, including the query params.  

If you don't care about the protocol and domain, use the original_fullpath or the fullpath method on the request. It returns the path including params.

# get "/articles"
request.fullpath # => "/articles"

# get "/articles?page=2"
request.fullpath # => "/articles?page=2"

Here's some other information available on the request object.

Property of requestPurpose
hostThe hostname used for this request.
domain(n=2)The hostname's first n segments, starting from the right (the TLD).
formatThe content type requested by the client.
methodThe HTTP method used for the request.
get?, post?, patch?, put?, delete?, head?Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD.
headersReturns a hash containing the headers associated with the request.
portThe port number (integer) used for the request.
protocolReturns a string containing the protocol used plus "://", for example "http://".
query_stringThe query string part of the URL, i.e., everything after "?".
remote_ipThe IP address of the client.
urlThe entire URL used for the request.