Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to page and send custom HTTP headers

Tags:

I use the following code to redirect to a page in PHP. I need to set a custom HTTP headers to pass along with the redirect.

header("Location: http://..."); 

How can I archive this?

like image 933
Lennie Avatar asked Sep 28 '11 12:09

Lennie


People also ask

Can you add headers to a redirect?

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.

What HTTP header do I use to redirect to another URL?

In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3 , and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header.

Can HTTP headers be custom?

There are many uses for custom headers and they are quite commonly used. Even if you aren't using a CDN or haven't specifically defined any custom HTTP headers on your origin server, you may still be sending responses with custom headers.

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.


1 Answers

I'm afraid, all the answers are wrong and misleading!

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.

You might be thinking that using multiple header() calls should work just fine. But it won't. 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. And it needs CORS implemented on the target server to allow such ajax requests.

Please note that a page can not set HTTP request headers unless it's making an async request using XMLHttpRequest. Meaning that you can't do such redirection with the custom header on the client-side as well.

like image 199
sepehr Avatar answered Sep 29 '22 09:09

sepehr