Read more

Escape a string for transportation in a URL

Henning Koch
September 24, 2015Software engineer at makandra GmbH

To safely transport an arbitrary string within a URL, you need to percent-encode Show archive.org snapshot characters that have a particular meaning in URLs, like & or =.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

If you are using Rails URL helpers like movies_path(:query => ARBITRARY_STRING_HERE), Rails will take care of the encoding for you. If you are building URLs manually, you need to follow this guide.

Ruby

In Ruby, use CGI.escape:

CGI.escape('foo=foo&bar=bar')
=> "foo%3Dfoo%26bar%3Dbar"

Do not ever use URI.encode or its alias URI.escape, which keeps control characters like & or = unescaped:

URI.encode('foo=foo&bar=bar')
=> "foo=foo&bar=bar"

Javascript

In Javascript, use encodeURIComponent:

encodeURIComponent('foo=foo&bar=bar')
=> "foo%3Dfoo%26bar%3Dbar"

Do not ever use encodeURI, which keeps control characters like & or = unescaped:

encodeURI('foo=foo&bar=bar')
=> "foo=foo&bar=bar"
Posted by Henning Koch to makandra dev (2015-09-24 14:53)