Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created January 29, 2016 21:07
Show Gist options
  • Save DinoChiesa/40f957479edb346de6c8 to your computer and use it in GitHub Desktop.
Save DinoChiesa/40f957479edb346de6c8 to your computer and use it in GitHub Desktop.
Use PHP code to force Wordpress to redirect to a secure site
/*
* 2016 Jan 29
*
* For redirecting to SSL site, from within PHP.
*
* This is useful if:
* - Your site is running behind a load-balancer, which
* means you cannot directly infer HTTPS, AND
* - you don't have the ability to modify
* .htaccess on your hosted site.
*
* Add this to your theme header, or similar.
* The code must run before any content is emitted,
* because a redirect won't work after that.
*
*/
function so_site_wants_ssl() {
// get_site_url() is actual url used.
// get_home_url() is url configured in the WP settings panel
$my_scheme = substr(get_home_url(), 0, 6);
return (strcasecmp($my_scheme, "https:") == 0) ;
}
function smarter_is_ssl_behind_lb() {
return (is_ssl() &&
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'));
}
function so_maybe_redirect_to_ssl_site() {
// force ssl if site is configured for SSL and if user is not using SSL
if (so_site_wants_ssl()) {
// site desires https access
if (!smarter_is_ssl_behind_lb()) {
// runtime thinks it is not being accessed via SSL
// redirect to secure endpoint
wp_redirect(get_home_url());
exit;
}
$_SERVER['HTTPS']='on'; // make is_ssl() do the right thing
}
}
so_maybe_redirect_to_ssl_site();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment