How to Get the Current Absolute URL in Rails
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 # => "http://www.example.com/articles?page=2"
Here's the source code for this method.
def original_url
base_url + original_fullpath
end
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 | Purpose |
|---|---|
| The hostname used for this request. |
| The hostname's first |
| The content type requested by the client. |
| The HTTP method used for the request. |
| Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
| Returns a hash containing the headers associated with the request. |
| The port number (integer) used for the request. |
| Returns a string containing the protocol used plus "://", for example "http://". |
| The query string part of the URL, i.e., everything after "?". |
| The IP address of the client. |
| The entire URL used for the request. |
Sign up for my newsletter
Let's learn to become better developers.