Martin
Martin

Reputation: 11336

In Rails, how to get current URL (but no paths)

If I'm in a URL such as

http://domain.example/mysite/bla

How can I request just the URL with no paths? Such as

http://domain.example

Upvotes: 55

Views: 41351

Answers (7)

Bishwas Bhandari
Bishwas Bhandari

Reputation: 51

Here's how you can get your current domain name.

Domain name

request.base_url 
# prod: https://example.com
# dev: https://localhost:8000

Getting full path

request.original_url
# prod: https://example.com/path/
# dev: https://localhost:8000/path/

Upvotes: 1

fl00r
fl00r

Reputation: 83680

You can use this

<%= request.protocol + request.host_with_port %>
#=> https://domain.example:3000
<%= request.protocol + request.host %>
#=> https://domain.example

Starting from Rails 3.2 you can also use

<%= request.base_url %>
#=> https://domain.example:3000

Upvotes: 120

kangkyu
kangkyu

Reputation: 6140

I think this can be useful too, if you're not in a controller.

URI.join(url_for(only_path: false), '/').to_s 

Upvotes: 0

Rohanthewiz
Rohanthewiz

Reputation: 975

If your port could be anything other than 80 it should be included.

"#{request.protocol}#{request.host_with_port}"

Upvotes: 0

Kulbir Saini
Kulbir Saini

Reputation: 3915

For protocol, domain and port

<%= "#{request.protocol + request.host}:#{request.port.to_s}" %>

Upvotes: 2

Pravin
Pravin

Reputation: 6662

request.host should do the trick, or:

request.port.blank? ? request.host : "#{request.host}: #{request.port}"

if you need to include the port too.

Upvotes: 5

Ashish
Ashish

Reputation: 5791

Try this

<%=request.scheme + '://' + request.host_with_port%>

If you want to see all available methods on request object then

<%=request.methods.sort%>

Upvotes: 4

Related Questions