Getting Server Domain Name in Sinatra
Was building a Sinatra app and needed to get the server's domain name dynamically. This is useful when you want to generate absolute URLs or when your app runs on different domains (development vs production).
Here are the different ways to get the domain name in Sinatra:
Method 1: Using request.host
get '/' do
"Server domain is: #{request.host}"
end
Method 2: Using request.url and parsing
get '/' do
domain = URI.parse(request.url).host
"Domain: #{domain}"
end
Method 3: For complete URL with protocol
get '/' do
base_url = "#{request.scheme}://#{request.host}"
base_url += ":#{request.port}" if request.port != 80
"Base URL: #{base_url}"
end
Method 4: Using request.host_with_port
get '/' do
"Server: #{request.host_with_port}"
end
Practical example - generating absolute URLs:
helpers do
def absolute_url(path)
"#{request.scheme}://#{request.host_with_port}#{path}"
end
end
get '/share' do
share_url = absolute_url("/posts/123")
"Share this: #{share_url}"
end
This is especially handy when:
- Generating email links
- Creating API responses with absolute URLs
- Building RSS feeds
- Handling OAuth redirects
Works great in both development (localhost:4567) and production environments.