Follow Redirects

The :follow_redirects plugin allows the client to send subsequent requests whenever the response is of the “Redirect” (3XX) variant.

res = HTTPX.get("https://google.com") #=> 301 response, location "https://www.google.com"
res = HTTPX.plugin(:follow_redirects).get("https://google.com") #=> 200 response from "https://www.google.com"

:max_redirects

It also allows one to set the maximum number of redirects (default is 3):

http = HTTPX.plugin(:follow_redirects)

http.max_redirects(42).get("https://example.com/redirect41times")
# or
http.get("https://example.com/redirect41times", max_redirects: 42)

:follow_insecure_redirects

By default, insecure redirects (https to http) aren’t followed. If you want to allow them however, you can enable this option:

http = HTTPX.plugin(:follow_redirects)
http.get("https://redirecttohttp", follow_insecure_redirects: true)

redirect_on

(introduced on httpx 1.2.0.)

In case you need to stop the redirect chain based on your rules (such as domain whitelisting), you can use the :redirect_on option:

allow_list = ->(redirect_uri) { ALLOW_LIST.include?(redirect_uri.host) }

http = HTTPX.plugin(:follow_redirects).with(redirect_on: allow_list)
http.get("https://redirecttohttp")

Retry-After

Response redirection will be delayed if the redirect response carries a retry-after header. The delay will be based on its value and some jitter. This is a standard way the server communicates to the client how long to wait before doing the next request.

FAQ

How can I get the sequence of redirect responses?

You can us event callbacks to collect them:

responses = []
HTTPX.plugin(:follow_redirects).plugin(:callbacks).on_response_completed do |req, res|
  responses << res
end.get("https://google.com")

responses.map(&:status) #=> [301, 200]

Next: Retries