Drupal and Secure Logins using mod_rewrite and manually setting the cookie

I never dug into mod_rewrite before Drupal. Now I do. I hope that I have explained this properly and that it helps others figure things out.

So here is the scenario:

  • logins should occur via SSL
  • everything else should occur via non-ssl
  • the main site is www.example.com
  • the ssl site is ssl.example.com

Normally, I understand that this is an easy process to accomplish if the third level domains match. In my case, this isn't true. I have a pre-existing certificate that I didn't want to burn and I personally prefer that my ssl site NOT use www as the hostname.

So this takes modifications in four different areas:

  • virtual host configuration for non-ssl site
  • virtual host configuration for the ssl site
  • manually setting the cookie in settings.php
  • install the module, securepages
  1. The following lines will modify port 80 traffic and URLs that are routed to this virtual host. Add these lines to your non-ssl config in the mod_rewrite section:

    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^.*$ http://www.example.com%{REQUEST_URI} [L,R=301]
    RewriteCond %{SERVER_PORT} !^80$
    RewriteRule ^.*$ http://www.example.com/%{REQUEST_URI} [L,R=301]

  2. The following lines will modify port 443 traffic and URLs that are routed to this virtual host. Add these lines to your ssl config in the mod_rewrite section:

    RewriteCond %{HTTP_HOST} !^ssl\.example\.com$ [NC]
    RewriteRule ^.*$ https://ssl.example.com%{REQUEST_URI} [L,R=301]
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^.*$ https://ssl.example.com/%{REQUEST_URI} [L,R]
  3. Add this to your setting.php file for this Drupal site:
    ini_set('session.cookie_domain', ".example.com");
  4. I won't explain how to install the securepages module. I assume you got here by knowing enough about Drupal. :) But, once you do install it, configure it to check the box about *using http whenever possible* checkbox. The reset of default settings that come with the module should work fine.

Enjoy!

( partial credit goes to souvent22 and others in IRC)

Submitted by davea on Wed, 2007-08-29 23:34. categories [ ]