I've created a plugin that turns all links into protocol relative URLs, like so:
http://example.com -> //example.com
I'm also adding a function to force HTTPS only if SSL is enabled and set up properly on the website. The following function below will force HTTPS regardless if it has been set up correctly:
add_action ( 'template_redirect', 'force_https', 1 );
function force_https() {
if ( ! is_ssl() ) {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit();
}
}
However, if SSL hasn't been configured for the website, it will cause a connection error and the user won't be able to access their website. This is where I want to put a check before it executes the wp_redirect()
.
My idea is to check if the get_home_url()
option has https://
in the URL:
if ( preg_match( '/https:\/\//', site_url() ) && ! is_ssl() ) {
Is there a better way to check? Or is it not even necessary to force HTTPS if my first function from my plugin has made all of the links protocol-relative?
is_ssl()
; it is also testing the$_SERVER
global so not sure you also need to do that. Also, I believe this is ok for the vast majority of cases but some server configs might not play nicely with the way the global gets set. Is an alternative to force your user to select an option that says "yes, I am using SSL", in your plugin settings page? (edit) one more point - you can always use protocol-relative URL references in your plugin. E.g.: "//foo.com/folder/resource..." and avoid any hard-coding of protocol.//
(protocol-relative), it's a matter of making sure the home/site URL is set up with HTTPS to enforce SSL.