Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect_to with HTTP header

Not sure if this is possible or makes any sense, but I'm trying to make a redirect after setting a HTTP header field. Something like:

request.headers['Accept'] = 'application/json'
redirect_to url

Obviously this doesn't work, as request is the current request, not the redirect. Is there any way to call redirect_to with custom HTTP headers?

like image 665
samvermette Avatar asked Sep 20 '12 01:09

samvermette


People also ask

Can you redirect with headers?

Redirection in PHP can be done using the header() function. To setup, a simple redirect simply creates an index.

How do I redirect a URL to another URL?

Add a new URL redirectClick the URL Redirects tab. In the upper right, click Add URL redirect. In the right panel, select the Standard or Flexible redirect type. A standard redirect is used to redirect one URL to another.


2 Answers

It's impossible to redirect to a page with custom headers set, no matter what language or framework you use. In other words, there's no way to trigger an HTTP redirect and cause the client (browser) to add a custom header.

As you yourself mentioned, you're setting the custom headers for the response which is instructing the browser to redirect, not for the redirect itself.

The only way for a site to instruct a browser to issue an HTTP request with a custom header is to use Javascript and the XMLHttpRequest object.

like image 111
sepehr Avatar answered Oct 05 '22 02:10

sepehr


Use the response object ...

If you want to set custom headers for a response then response.headers is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to response.headers this way:

response.headers["Content-Type"] = "application/pdf"

like image 21
King'ori Maina Avatar answered Oct 05 '22 02:10

King'ori Maina