So I am working on making a custom theme and set of plugins for a WordPress blog. I had the need to make sure that users that were logged in were using HTTPS and not just HTTP. I came up with a quick little function that will do just that. I added this block of code to the top of the themes header.php file within php tags and it gave me the desired effect:
// This forces logged in users to use HTTPS if (is_user_logged_in() && ($_SERVER['SERVER_PORT'] !== '443')){ wp_redirect("https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']); }
You may need to adjust the code a little depending on what web server you are running and what headers get set, but this is working great for me running on an nginx web server with PHP 5.3. Basically it just checks to see if the user is logged in and they are on a port other than 443 (443 is the port number used by HTTPS). If both of those are true then it redirects them to the HTTPS version of the page.
Granted you will need to have HTTPS working properly before you can use this, so you need certificates and a proper web server configuration.
Let me know if you have a better way of doing this. And no… the WordPress HTTPS plugin does not count. It is far too heavy for this requirement of just ensuring that all logged in users are on HTTPS at all times. If I needed more fine-tuned control then sure I would go for it 😉
X3mE says:
Hi,
Thank you for your post! My only question is – will this work on IIS?
cryptk says:
It should, all of this is done in PHP and as such should be server agnostic 😉
Lillie Maxwell says:
I have tried it and it works on IIS. THanks
Bruce says:
Thank you so much for this. I searched for hours to try to find out how to do this and you have got the right stuff here. Works great.
I’m not sure if I’m being overly paranoid about having people using their log in over an insecure connection (public wi-fi) but I felt that everything while logged in should be encrypted.
I do have a question you might be able to answer, if someone logs in and visits various parts of the site, they will be using https, thanks to your code, but once they log out, if they continue to move throughout the site or come back in the same browser session without logging back in they will be in an insecure area.
My question is whether or not they might be transmitting any cookies or other information at that point that would be compromising. I’m not sure if there are any logged in session cookies that WordPress uses while logged in that are not flushed when someone logs out…
cryptk says:
I'm actually not certain if all of the cookies are flushed or not. It is pretty trivial to force the whole site to HTTPS though using different site names in the wordpress configuration, mod_rewrite, plugins etc. Because of how trivial that is, I decided to write the article on how to do it for logged in users only without a plugin.