WordPress – Seamless Optional SSL

Recently I ran into a problem where I needed a site that would support SSL, optionally (for a Facebook application). The site needed to stay in SSL if that’s what was requested, and stay in non-SSL if that’s what was requested. The problem I ran into was that WordPress generated URLs would either point to HTTP or HTTPS depending on my config, and that links in content would only point to one or the other.

I wrote the below snippet to fix the issue. Just throw this in your wp-config.php file!

  $_SERVER['HTTPS'] = 'on';

if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  $protocol = 'https://';
} else {
  $protocol = 'http://';

define('WP_SITEURL', $protocol . $_SERVER['SERVER_NAME']);
define('WP_HOME', WP_SITEURL);

ob_start(function($buffer) {
  $http  = str_replace('https://', 'http://', WP_SITEURL);
  $https = str_replace('http://', 'https://', WP_SITEURL);

  if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
    $search  = $http;
    $replace = $https;
  } else {
    $search  = $https;
    $replace = $http;

  return str_replace($search, $replace, $buffer);

One Reply to “WordPress – Seamless Optional SSL”

  1. […] I added Brandon Wambloldt’s Code for optional TLS. […]

Leave a Reply