Nginx and SSL – PHP Redirect Loops

Small post, I’ve been struggling a little with getting ssl to work reliably with https. specifically relating to the following piece of code:

[code]fastcgi_param   HTTPS   on;[/code]

Lets wind back, I can get HTTPS working with nginx no problem and the above provided I do the following, maintain 2 vhosts for the same domain, one for http and one for https. The only difference is that the above line is present in the HTTPS vhost’s PHP block.

However thats messy, I either have to maintain 2 vhosts or then deal with extra includes, which just asks for trouble to maintain. Nginx has supported combined HTTP and HTTPS vhosts for some time, so I looked at how I could make this work within a combined vhost. with a little bit of IF magic (yes I know ifisevil) I can add the following to my fastcgi_params file and just forget about it 🙂

[code]set $ssl off;

if ($ssl_protocol != “” ) {
set $ssl on;
}

fastcgi_param   HTTPS                   $ssl;[/code]

Now PHP scripts will correctly detect SSL status and work correctly, no nasty redirect loops (particularly with WordPress) and nice clean vhosts and easy management. Hopefully the great team at Nginx can convert this bit of code into an actual variable in the SSL module which would probably be faster at higher traffic levels

Posted in HOWTO's, Performance & Optimisation
Tags: , , , , ,
2 comments on “Nginx and SSL – PHP Redirect Loops
  1. gOA-pSY says:

    You can use the “map” directive to skip “if”:

    // http context
    map $scheme $ssl_enabled {
    default off;
    https on;
    }

    // location context
    fastcgi_param HTTPS $ssl_enabled;

    • didnt think of that, looks much cleaner too, shall test quickly, only caveat is the code is broken down into 2 places so have to remember to insert the code in both places, but looks like a much more efficient solution

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.