Tell nginx to SSL encrypt specific PHP documents

I have set up my server with the following settings:

server {
   server_name www.example.com
   listen 443;
   listen 80;

   location /login\.php
   {
   rewrite ^(.*) https://www.example.com/login.php$1 last;        
   }

   .. other settings
}

However, with this setup I receive a redirect error (too many redirects). Is there a way to tell nginx that if I have the file login.php that I want SSL and all other files are being served without it?


Solution 1:

Since nginx 0.7.14, you may create compact configuration for http and https serving without splitting into separate server {} bocks:

listen 80;
listen 443 ssl;

# rest ssl configuration...

If you want to protect several locations - just check sсheme and do redirect with "return" or "rewrite":

location = /login.php {

      if($scheme = "http") {
              rewrite ^ https://$host$request_uri? permanent;
      }

      ...
}

Solution 2:

You can (see the other answer), but it's generally a better idea to encrypt everything - transferring username and password securely and then giving them a full-account-access cookie in plaintext is almost as dangerous as not encrypting at all.

As an example of just how dangerous it is, see here for a program which automatically owns twitter / facebook / google / etc users by taking advantage of this mistake --> http://codebutler.com/firesheep