SSL detection by PHP scripts run through FastCGI on nginx

How’s that title for acronym soup?

I ran across this issue when playing around with nginx. I was trying to set up phpMyAdmin for SQL administration, but ran into a rather peculiar issue. To explain the problem, let me give you some context.

I’m running nginx only on port 443, using SSL for everything. As I’m going through the setup for phpMyAdmin, imagine my surprise when it alerts me that I’m not using an SSL connection. In fact, it’s impossible for me not to use SSL, because there’s no regular HTTP server running on port 80. I continued with the setup anyway, checking the ForceSSL option which requires all phpMyAdmin requests to be done over SSL. When I finished installing it and tried to log in, I got a Firefox error that it was stuck in a redirect loop.

Much Google searching later, I still couldn’t find the problem. This was when I remembered that PHP is configured differently on nginx that is typically done with Apache. With Apache, many people use the mod_php module that compiles PHP support directly into the server. With nginx, you generally process PHP requests using FastCGI.

I wondered if perhaps the fact that the connection was taking place over SSL wasn’t being passed through to the FastCGI process. If that was the case, the phpMyAdmin setup script wouldn’t know it was being invoked over HTTPS, and when you tried to log in it would try to forward you to the HTTPS url, which is the same page you had just requested. That would push you into an infite redirect loop.

In fact, that’s exactly what was happening. You can fix this with a simple addition to your nginx.conf file:

server {
    listen 443;
    ... more config here, include SSL ...
    location ~ \.php$ {
        ... FastCGI config here ...
        fastcgi_param HTTPS on;
    }
}

That fastcgi_param HTTPS on; line does the trick. Now the PHP script knows it’s being invoked over SSL and doesn’t try to infinitely redirect you. Awesome.

This entry was posted in Linux, Scripting, Security. Bookmark the permalink.

3 Responses to SSL detection by PHP scripts run through FastCGI on nginx

  1. vbm says:

    UNBELIEVABLE! I spent two days on this issue… Thank you so much for sharing this!

  2. Naguissa says:

    Awesome! This is just what I need! Thank you a lot.

  3. Laurent F says:

    I had this same issue and wanted to thank you for sharing the fix. Great.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>