full of … these

Redirect http to https behind varnish for php services

Posted: July 21st, 2011 | Author: | Filed under: howto | Tags: , , | 1 Comment »

It may happen to want to redirect a site from http to https behind a varnish cache system.

Is known the fact that varnish has a lack of redirect procedures, mostly from http to https.

A redirect on varnish from http to https looks like this:

if (req.http.host ~ "^(www\.)?site\.com$" && req.url ~ "\/checkout\/cart") {
       error 750 "https://www.site.com/checkout/cart";
sub vcl_error {
 #redirect to https
 if (obj.status == 750) {
 set obj.http.Location = obj.response;
 set obj.status = 302;

That will not work!

Varnish is not aware if the request was made from http (request directly sent to varnish) or https (request sent to pound).

So, I have found another page suggesting that the redirect can be added to php like this:

if (($_SERVER['REQUEST_URI'] == '/admin' || $_SERVER['REQUEST_URI'] ==  '/checkout/cart/') && !$_SERVER['HTTP_X_FORWARDED_PROTO']){
  header("Location: https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
}elseif (($_SERVER['REQUEST_URI'] != '/admin' && $_SERVER['REQUEST_URI'] != '/checkout/cart/') && $_SERVER['HTTP_X_FORWARDED_PROTO']) {
  header("Location: http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);

This code fixes https redirection.
Any comments are welcome. I am new to varnish.

One Comment on “Redirect http to https behind varnish for php services”

  1. 1Jetsyn said at 12:04 pm on August 13th, 2011:

    A few years ago I’d have to pay someone for this infmortiaon.

Leave a Reply