Parsing URLs

suggest change

A URL packs several pieces of information into one string:

  https://alice:s3cret@www.example.com:8443/docs/guide.html?lang=en&page=2#install
  \___/   \__________/ \_____________/ \__/\______________/ \____________/ \_____/
 scheme     userinfo        host       port      path            query    fragment

Ruby's standard library has the uri module (it's a default gem, so a plain require 'uri' works) for splitting URLs into components, changing them, building new ones, encoding query strings and resolving relative links. This article covers URI in depth, then shows where Rack and the addressable gem fill the gaps.

The examples were run with Ruby 4.0 (uri 1.1), rack 3.2 and addressable 2.9.

Parsing a URL into components

URI(str) and URI.parse(str) do the same thing: parse a string and return a URI object with a reader for each component:

require 'uri'

uri = URI('https://alice:s3cret@www.example.com:8443/docs/guide.html?lang=en&page=2#install')

puts uri.class
puts "scheme:   #{uri.scheme}"
puts "userinfo: #{uri.userinfo}"
puts "user:     #{uri.user}"
puts "password: #{uri.password}"
puts "host:     #{uri.host}"
puts "port:     #{uri.port}"
puts "path:     #{uri.path}"
puts "query:    #{uri.query}"
puts "fragment: #{uri.fragment}"
puts "request_uri: #{uri.request_uri}"
puts "origin:   #{uri.origin}"
puts "authority: #{uri.authority}"
p uri.select(:scheme, :host, :port)
URI::HTTPS
scheme:   https
userinfo: alice:s3cret
user:     alice
password: s3cret
host:     www.example.com
port:     8443
path:     /docs/guide.html
query:    lang=en&page=2
fragment: install
request_uri: /docs/guide.html?lang=en&page=2
origin:   https://www.example.com:8443
authority: www.example.com:8443
["https", "www.example.com", 8443]

request_uri (path plus query) is what goes on the first line of an HTTP request, and origin (scheme, host and port) is what browsers use for same-origin checks. Both exist only on URI::HTTP and its subclasses. The query is returned as one raw string. The "Query strings" section below shows how to turn it into key/value pairs.

URI() also accepts a URI object and returns it unchanged, so methods can take either a string or a URI:

def fetch(url)
  uri = URI(url) # works for 'https://...' and for URI objects
  # ...
end

URI classes and default ports

The class of the result depends on the scheme. Each class knows its scheme's default port and which components make sense:

require 'uri'

%w[
  http://example.com
  https://example.com/
  ftp://ftp.example.com/pub/file.txt
  mailto:bob@example.com?subject=Hi
  file:///C:/Users/bob/notes.txt
  ws://localhost:3000/cable
  urn:isbn:0451450523
  /relative/path?x=1
  //cdn.example.com/app.js
].each do |s|
  u = URI(s)
  printf "%-38s %-14s scheme=%-8p host=%-19p port=%-5p path=%p\n",
         s, u.class, u.scheme, u.host, u.port, u.path
end
http://example.com                     URI::HTTP      scheme="http"   host="example.com"       port=80    path=""
https://example.com/                   URI::HTTPS     scheme="https"  host="example.com"       port=443   path="/"
ftp://ftp.example.com/pub/file.txt     URI::FTP       scheme="ftp"    host="ftp.example.com"   port=21    path="pub/file.txt"
mailto:bob@example.com?subject=Hi      URI::MailTo    scheme="mailto" host=nil                 port=nil   path=nil
file:///C:/Users/bob/notes.txt         URI::File      scheme="file"   host=""                  port=nil   path="/C:/Users/bob/notes.txt"
ws://localhost:3000/cable              URI::WS        scheme="ws"     host="localhost"         port=3000  path="/cable"
urn:isbn:0451450523                    URI::Generic   scheme="urn"    host=nil                 port=nil   path=nil
/relative/path?x=1                     URI::Generic   scheme=nil      host=nil                 port=nil   path="/relative/path"
//cdn.example.com/app.js               URI::Generic   scheme=nil      host="cdn.example.com"   port=nil   path="/app.js"

Things to note:

Some classes have their own readers:

require 'uri'

mail = URI('mailto:bob@example.com?subject=Hi')
p mail.to, mail.headers
p URI('urn:isbn:0451450523').opaque
p URI('/relative/path').absolute?, URI('/relative/path').relative?
"bob@example.com"
[["subject", "Hi"]]
"isbn:0451450523"
false
true

Invalid URLs

URI.parse raises URI::InvalidURIError (a subclass of URI::Error, which is a StandardError) when the string isn't a valid URI:

require 'uri'

[
  'http://exa mple.com',
  'https://example.com/a b',
  'http://example.com/ünï',
  'http://example.com/%zz',
  'http://[::1',
  ' https://example.com',
  'not a url',
  'example.com/path',
  'javascript:alert(1)',
  'http://example.com:99999',
  ''
].each do |s|
  u = URI.parse(s)
  puts "#{s.inspect} => #{u.class} host=#{u.host.inspect} path=#{u.path.inspect}"
rescue URI::InvalidURIError => e
  puts "#{s.inspect} => #{e.class}: #{e.message}"
end
"http://exa mple.com" => URI::InvalidURIError: bad URI (is not URI?): "http://exa mple.com"
"https://example.com/a b" => URI::InvalidURIError: bad URI (is not URI?): "https://example.com/a b"
"http://example.com/ünï" => URI::InvalidURIError: URI must be ascii only "http://example.com/\u00FCn\u00EF"
"http://example.com/%zz" => URI::InvalidURIError: bad URI (is not URI?): "http://example.com/%zz"
"http://[::1" => URI::InvalidURIError: bad URI (is not URI?): "http://[::1"
" https://example.com" => URI::InvalidURIError: bad URI (is not URI?): " https://example.com"
"not a url" => URI::InvalidURIError: bad URI (is not URI?): "not a url"
"example.com/path" => URI::Generic host=nil path="example.com/path"
"javascript:alert(1)" => URI::Generic host=nil path=nil
"http://example.com:99999" => URI::HTTP host="example.com" path=""
"" => URI::Generic host=nil path=""

The parser is strict about characters: spaces, non-ASCII characters and broken % escapes are errors, and so is surrounding whitespace, so strip user input first. On the other hand, many strings that you wouldn't call a URL parse without complaint. example.com/path is a relative path with no host, javascript:alert(1) is a valid URI, and the port isn't range checked. "It parses" doesn't mean "it's a web URL you can fetch". Check the parts you need:

require 'uri'

def web_url?(str)
  uri = URI.parse(str.strip)
  uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.port.between?(1, 65_535)
rescue URI::InvalidURIError
  false
end

[
  'https://example.com/path',
  'http://localhost:3000',
  '  https://example.com  ',
  'HTTPS://EXAMPLE.COM',
  'example.com',
  'ftp://example.com',
  'javascript:alert(1)',
  'https:///nohost',
  'http://example.com:99999',
  'https://exa mple.com'
].each { |s| printf "%-28p %s\n", s, web_url?(s) }
"https://example.com/path"   true
"http://localhost:3000"      true
"  https://example.com  "    true
"HTTPS://EXAMPLE.COM"        true
"example.com"                false
"ftp://example.com"          false
"javascript:alert(1)"        false
"https:///nohost"            false
"http://example.com:99999"   false
"https://exa mple.com"       false

Since Ruby 3.4 URI.parse uses an RFC 3986 parser (URI::DEFAULT_PARSER is a URI::RFC3986_Parser). The older RFC 2396 parser is still available as URI::RFC2396_PARSER. It is stricter in places, for example it rejects | in a query string, which the new parser accepts. Use the default unless you need to match old behavior.

Hosts, IPv6 and case

require 'uri'

u = URI('http://[::1]:8080/status')
p u.host, u.hostname, u.port

u = URI('HTTP://www.Example.COM:80/a/b')
p u.scheme, u.host
p u.normalize.to_s
p u == URI('http://www.example.com/a/b')
p URI('https://example.com:443/').to_s
"[::1]"
"::1"
8080
"http"
"www.Example.COM"
"http://www.example.com/a/b"
true
"https://example.com/"

Percent-encoding

Characters that aren't allowed in a URL are written as % followed by two hex digits of their UTF-8 bytes. Which characters must be encoded depends on where the text goes, so uri has two pairs of functions:

require 'uri'

s = 'Zoë & co/a+b?=#'
p URI.encode_www_form_component(s) # for query strings and HTML forms
p URI.encode_uri_component(s)      # for any other component, like a path segment
p URI.decode_www_form_component('Zo%C3%AB+%26+co')
p URI.decode_uri_component('Zo%C3%AB+%26+co')
"Zo%C3%AB+%26+co%2Fa%2Bb%3F%3D%23"
"Zo%C3%AB%20%26%20co%2Fa%2Bb%3F%3D%23"
"Zoë & co"
"Zoë+&+co"

The only difference is the space: the www_form functions follow the HTML form encoding, where a space is +, while the uri_component functions use %20 and leave + alone when decoding. A + in a path is a literal plus, so decoding a path with decode_www_form_component would corrupt it.

The parsed path keeps its escapes, decode it yourself when you need the real file name:

require 'uri'

uri = URI('https://example.com/files/2026%20Q3%2Bnotes.pdf')
p uri.path
p URI.decode_uri_component(File.basename(uri.path))

# Encoding user input into a path: encode each segment separately
name = 'reports/2026 Q3.pdf'
p "/files/#{URI.encode_uri_component(name)}"
p '/files/' + name.split('/').map { URI.encode_uri_component(it) }.join('/')
"/files/2026%20Q3%2Bnotes.pdf"
"2026 Q3+notes.pdf"
"/files/reports%2F2026%20Q3.pdf"
"/files/reports/2026%20Q3.pdf"

Encoding the whole value turns / into %2F, so the server sees one segment. Splitting first keeps the slashes as separators. Which one you want depends on whether / in the value means "subdirectory" or is just part of the name.

URI.escape and URI.encode, which you'll find in old answers online, were removed in Ruby 3.0. They encoded a whole URL at once, which can't be done correctly because it's ambiguous whether a & or / is data or a separator. CGI.escape still exists in Ruby 4.0 (via require 'cgi/escape') and gives the same result as URI.encode_www_form_component, but CGI.parse is gone along with the rest of the cgi library.

Query strings

URI.decode_www_form splits a query string into an array of [key, value] pairs, decoding both:

require 'uri'

query = 'q=ruby+uri&tag=web&tag=net&empty=&flag&name=Zo%C3%AB%20K'
pairs = URI.decode_www_form(query)
p pairs
p pairs.to_h
p pairs.group_by(&:first).transform_values { |v| v.map(&:last) }
[["q", "ruby uri"], ["tag", "web"], ["tag", "net"], ["empty", ""], ["flag", ""], ["name", "Zoë K"]]
{"q" => "ruby uri", "tag" => "net", "empty" => "", "flag" => "", "name" => "Zoë K"}
{"q" => ["ruby uri"], "tag" => ["web", "net"], "empty" => [""], "flag" => [""], "name" => ["Zoë K"]}

It returns an array because keys can repeat and their order can matter. to_h keeps only the last value of a repeated key. Group the pairs when you need all of them.

URI.encode_www_form goes the other way. It accepts a hash or an array of pairs, expands array values into repeated keys and writes a key without = for nil:

require 'uri'

p URI.encode_www_form(q: 'ruby uri', tag: %w[web net], page: 2, flag: nil, name: 'Zoë & co')
p URI.encode_www_form([['b', '2'], ['a', '1'], ['b', '3']])
"q=ruby+uri&tag=web&tag=net&page=2&flag&name=Zo%C3%AB+%26+co"
"b=2&a=1&b=3"

Decoding is lenient, which matters for input from users: an invalid escape is left as-is and invalid UTF-8 is replaced with U+FFFD instead of raising. The lower-level decode_www_form_component does raise:

require 'uri'

p URI.decode_www_form('a=%zz&b=%E2%82')
begin
  URI.decode_www_form_component('%zz')
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
p URI.decode_www_form('a=1;b=2')
p URI.decode_www_form('a=1;b=2', separator: ';')
[["a", "%zz"], ["b", "�"]]
ArgumentError: invalid %-encoding (%zz)
[["a", "1;b=2"]]
[["a", "1"], ["b", "2"]]

Nested parameters with Rack

URI knows nothing about the user[name]=... and tags[]=... conventions used by Rails, Sinatra and other Rack frameworks. Rack::Utils parses and builds them:

require 'rack'

q = 'user[name]=Zo%C3%AB&user[roles][]=admin&user[roles][]=dev&page=2&tag=a&tag=b'
p Rack::Utils.parse_nested_query(q)
p Rack::Utils.parse_query('tag=a&tag=b&page=2')
puts Rack::Utils.build_nested_query(user: { name: 'Zoë', roles: %w[admin dev] }, page: 2)
{"user" => {"name" => "Zoë", "roles" => ["admin", "dev"]}, "page" => "2", "tag" => "b"}
{"tag" => ["a", "b"], "page" => "2"}
user%5Bname%5D=Zo%C3%AB&user%5Broles%5D%5B%5D=admin&user%5Broles%5D%5B%5D=dev&page=2

parse_nested_query keeps only the last value of a repeated plain key (tag), while parse_query collects repeated keys into an array. Inside a Rack app you rarely call these yourself: Rack::Request#params, #path, #host and friends already give you the parsed pieces of the request URL.

Changing and building URLs

URI objects are mutable and have a setter for each component. Use dup to keep the original:

require 'uri'

base = URI('https://api.example.com/v1/users?page=1')
u = base.dup
u.path = '/v2/users'
u.query = URI.encode_www_form(page: 3, per_page: 50)
u.fragment = 'top'
u.port = 8080
puts u
puts base

begin
  u.path = 'no-leading-slash'
rescue URI::InvalidComponentError => e
  puts "#{e.class}: #{e.message}"
end

begin
  u.host = 'bad host'
rescue URI::InvalidComponentError => e
  puts "#{e.class}: #{e.message}"
end
https://api.example.com:8080/v2/users?page=3&per_page=50#top
https://api.example.com/v1/users?page=1
URI::InvalidComponentError: bad component(expected absolute path component): no-leading-slash
URI::InvalidComponentError: bad component(expected host component): bad host

The setters validate their input but don't encode it, so pass already-encoded values (that's what encode_www_form is for in the query= line).

Don't change the scheme of an existing object. The class (and with it the default port) stays the same, so you end up with an object that disagrees with its own string form:

require 'uri'

u = URI('https://a.com/x')
u.scheme = 'http'
p u.class, u.port, u.to_s, URI(u.to_s).port
URI::HTTPS
443
"http://a.com/x"
80

To build a URL from parts, use the build class method of the right class. It also validates, and expects encoded components:

require 'uri'

puts URI::HTTP.build(host: 'localhost', port: 3000, path: '/health')
puts URI::HTTPS.build(host: 'example.com', path: '/search',
                      query: URI.encode_www_form(q: 'ruby & rails'))
puts URI::HTTPS.build(host: 'example.com', path: "/#{URI.encode_uri_component('café menu')}")

begin
  URI::HTTPS.build(host: 'example.com', path: '/a b')
rescue URI::InvalidComponentError => e
  puts "#{e.class}: #{e.message}"
end
http://localhost:3000/health
https://example.com/search?q=ruby+%26+rails
https://example.com/caf%C3%A9%20menu
URI::InvalidComponentError: bad component(expected absolute path component): /a b

A common task is adding or replacing query parameters on a URL you didn't create. Decode the existing query, change the pairs and encode again, so existing parameters and the fragment survive:

require 'uri'

def with_params(url, **params)
  uri = URI(url)
  pairs = URI.decode_www_form(uri.query || '')
  params.each do |key, value|
    pairs.reject! { |k, _| k == key.to_s }
    pairs << [key.to_s, value]
  end
  uri.query = pairs.empty? ? nil : URI.encode_www_form(pairs)
  uri.to_s
end

puts with_params('https://example.com/list?sort=name&page=1', page: 2, q: 'café')
puts with_params('https://example.com/list#results', q: 'x')
https://example.com/list?sort=name&page=2&q=caf%C3%A9
https://example.com/list?q=x#results

Resolving relative URLs

Links in HTML pages, Location headers and API pagination links are often relative. base + ref (an alias for merge) resolves them the same way a browser does:

require 'uri'

base = URI('https://example.com/docs/guide/intro.html?x=1')
%w[
  setup.html
  ../api/index.html
  /about
  ?page=2
  #section-3
  //cdn.example.com/lib.js
  https://other.org/
  ../../../../etc
  .
].each do |ref|
  printf "%-26s => %s\n", ref, base + ref
end
setup.html                 => https://example.com/docs/guide/setup.html
../api/index.html          => https://example.com/docs/api/index.html
/about                     => https://example.com/about
?page=2                    => https://example.com/docs/guide/intro.html?page=2
#section-3                 => https://example.com/docs/guide/intro.html?x=1#section-3
//cdn.example.com/lib.js   => https://cdn.example.com/lib.js
https://other.org/         => https://other.org/
../../../../etc            => https://example.com/etc
.                          => https://example.com/docs/guide/

Merging also removes . and .. segments, which normalize doesn't do. route_to and route_from compute the reverse, the relative reference from one URL to another:

require 'uri'

a = URI('https://example.com/docs/guide/intro.html')
p a.route_to('https://example.com/docs/api/index.html').to_s
p (URI('https://example.com/') + 'a/b/../c/./d.html').to_s
"../api/index.html"
"https://example.com/a/c/d.html"

URI.join(base, *refs) merges several references in turn. It follows the same rules, which surprises people who expect it to work like File.join:

require 'uri'

puts URI.join('https://example.com/api/v1/', 'users/', '42')
puts URI.join('https://example.com/api/v1/', 'users', '42')
puts URI.join('https://example.com/api/v1', 'users')
puts URI.join('https://example.com/api/v1/', '/users')
https://example.com/api/v1/users/42
https://example.com/api/v1/42
https://example.com/api/users
https://example.com/users

The last segment of the base is a "file" unless it ends with /, so it gets replaced, and a reference starting with / replaces the whole path. When you put together API URLs, give the base a trailing slash and use relative paths, as the client in REST APIs does.

Extracting URLs from text

URI.extract and URI.regexp are obsolete and print warnings. They also grab trailing punctuation ("https://example.com/x)."). A simple pattern plus URI.parse as the validator works better:

require 'uri'

text = 'Docs at https://ruby-lang.org/en/documentation/. Mirror: http://example.com/a?b=1, ' \
       'or (see https://example.com/x). Bad: http://exa%zz.com/ and ftp://files.example.com'

urls = text.scan(%r{https?://\S+}).filter_map do |candidate|
  candidate = candidate.sub(/[.,;:!?)\]'"]+\z/, '')
  uri = URI.parse(candidate)
  uri.to_s if uri.host
rescue URI::InvalidURIError
  nil
end
puts urls
https://ruby-lang.org/en/documentation/
http://example.com/a?b=1
https://example.com/x

For links inside HTML, parse the HTML instead (see Parsing HTML) and resolve each href against the page URL with +.

Checking a redirect target

A login page that redirects to a ?return_to= parameter must make sure the target is on your own site, or attackers can use it to send users to a phishing page (an "open redirect"). String checks like start_with?('/') miss //evil.com, and checks like include?('app.example.com') miss app.example.com.evil.com. Resolve the value against your origin and compare origins:

require 'uri'

APP_ORIGIN = URI('https://app.example.com')

# Returns a same-origin path for a ?return_to= value, or '/'.
def safe_return_to(target)
  uri = APP_ORIGIN + URI.parse(target.to_s)
  return '/' unless uri.is_a?(URI::HTTP) && uri.origin == APP_ORIGIN.origin
  uri.request_uri + (uri.fragment ? "##{uri.fragment}" : '')
rescue URI::Error
  '/'
end

[
  '/account/settings?tab=email',
  'orders/42#items',
  'https://app.example.com/billing',
  'https://app.example.com.evil.com/',
  '//evil.com/phish',
  'https://evil.com@app.example.com/x',
  'https://app.example.com@evil.com/x',
  'javascript:alert(1)',
  '/\\evil.com',
  'http://app.example.com/',
  nil
].each { |t| printf "%-38p => %s\n", t, safe_return_to(t) }
"/account/settings?tab=email"          => /account/settings?tab=email
"orders/42#items"                      => /orders/42#items
"https://app.example.com/billing"      => /billing
"https://app.example.com.evil.com/"    => /
"//evil.com/phish"                     => /
"https://evil.com@app.example.com/x"   => /x
"https://app.example.com@evil.com/x"   => /
"javascript:alert(1)"                  => /
"/\\evil.com"                          => /
"http://app.example.com/"              => /
nil                                    => /

The function returns only a path, never a full URL, so even if a check were wrong the redirect would stay on your host. https://app.example.com@evil.com/x shows why you must compare the parsed host: everything before @ is userinfo, and the real host is evil.com. The same approach (parse, then check the scheme and host against an allow-list) applies when your server fetches URLs supplied by users. See Application security.

Addressable: Unicode, templates and lenient parsing

The addressable gem (gem install addressable) is a more complete URI implementation. It is used by many HTTP libraries, and you'll want it when you need:

require 'addressable/uri'

u = Addressable::URI.parse('https://münchen.example/straße/a b?q=café&tag=x&tag=y#top')
puts u.host
puts u.normalized_host
puts u.normalize
puts u.display_uri
p u.query_values
p u.query_values(Array)

puts Addressable::URI.parse('HTTP://Example.COM:80/a/./b/../c?b=2&a=1').normalize

u = Addressable::URI.parse('https://example.com/search')
u.query_values = { q: 'ruby uri', page: 2 }
puts u

puts Addressable::URI.heuristic_parse('example.com/path')
puts Addressable::URI.heuristic_parse('www.example.com')
münchen.example
xn--mnchen-3ya.example
https://xn--mnchen-3ya.example/stra%C3%9Fe/a%20b?q=caf%C3%A9&tag=x&tag=y#top
https://münchen.example/stra%C3%9Fe/a%20b?q=caf%C3%A9&tag=x&tag=y#top
{"q" => "café", "tag" => "y"}
[["q", "café"], ["tag", "x"], ["tag", "y"]]
http://example.com/a/c?b=2&a=1
https://example.com/search?page=2&q=ruby%20uri
http://example.com/path
http://www.example.com

The URL that the standard URI rejects is accepted here. normalize converts the host to its ASCII (Punycode) form, encodes the path and query, and removes dot segments. display_uri gives the form you'd show to a user. query_values= sorts the keys and encodes spaces as %20, and heuristic_parse adds a missing http:// the way a browser address bar does.

URI templates describe a family of URLs, and many APIs (GitHub's among them) publish their links in this format. expand fills in a template and encodes each value correctly for its position, and extract does the reverse, a small router:

require 'addressable/template'

t = Addressable::Template.new('https://api.example.com/repos/{owner}/{repo}/issues{?state,labels*,page}')
puts t.expand(owner: 'ruby', repo: 'ruby', state: 'open', labels: %w[bug help], page: 2)
puts t.expand(owner: 'a b', repo: 'x/y')
p t.variables

route = Addressable::Template.new('/users/{id}/posts/{post_id}')
p route.extract('/users/42/posts/7')
p route.extract('/users/42')
https://api.example.com/repos/ruby/ruby/issues?state=open&labels=bug&labels=help&page=2
https://api.example.com/repos/a%20b/x%2Fy/issues
["owner", "repo", "state", "labels", "page"]
{"id" => "42", "post_id" => "7"}
nil

Optional variables that you leave out disappear from the result along with their ?, & and =.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents