Using protocol-relative URIs within "Location:" headers
Asked Answered
C

2

10

I note in the PHP manual which states the following:

HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs.

To facilitate users with preference for a HTTPS everywhere connection, I am thinking of changing the headers in my PHP scripts from:

header("Location: http://www.example.com/"); to header("Location: //www.example.com/");

I have tested the above code to be working on my firefox browser, but I am not sure whether it is an advisable thing to do. Or whether I should extract the protocol from $_SERVER variable and put it in.

Chery answered 15/9, 2012 at 10:40 Comment(1)
possible duplicate of Is a 302 Redirect to relative URL valid, or invalid?Doran
A
9

The HTTPbis update allows relative URIs. While not specifically mentioned, this includes protocol-relative URLs.

(It's foremost an update to the HTTP/1.1 spec that documents established browser behaviour.)

Apiarian answered 15/9, 2012 at 10:54 Comment(2)
This is useful. Thanks. HTTP/1.1 has been here for a very long time. Can I say that such behaviour is already enforced by most modern browsers?Chery
I think it's pretty important to point out that the document you've linked to is (even now) only a draft! It won't be submitted to the IESG for consideration as a standard until September this year. In any case, what's most important to the OP here, I would think, is not what the spec says, but how browsers behave in reality.Brink
T
2

As suggested by HTTP protocol, you should use absolute URI. You can still detect protocol, by using $_SERVER['HTTPS'] variable, with a condition like:

$protocol = "http" . (!empty($_SERVER['HTTPS']) ? "s" : "");
Tashinatashkent answered 15/9, 2012 at 10:50 Comment(2)
Note that when using ISAPI with IIS, the value will be "off" if the request was not made through the HTTPS protocol. (Same behaviour has been reported for IIS7 running PHP as a Fast-CGI application).Lodi
This will not work if your app is running HTTP and is behind a reverse proxy that is using HTTPS.Dimercaprol

© 2022 - 2024 — McMap. All rights reserved.