Send every HTTP request to the HTTPS version using your site's own domain, not the request's Host header, and add an HSTS header.
add_action( 'template_redirect', function (): void {
$forwarded_https = 'https' === strtolower( (string) ( $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '' ) );
if ( is_ssl() || $forwarded_https || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
// Build the address from your own domain, never from the visitor's Host header.
$home = wp_parse_url( home_url() );
$host = $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );
wp_safe_redirect( 'https://' . $host . wp_unslash( $_SERVER['REQUEST_URI'] ?? '/' ), 301 );
exit;
}, 1 );
// Tell browsers to use HTTPS for the next year.
add_action( 'send_headers', function (): void {
if ( is_ssl() ) {
header( 'Strict-Transport-Security: max-age=31536000' );
}
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
If your site can still be reached over plain HTTP, visitors and search engines can end up on the insecure version. The best fix is a redirect at your host or CDN. When you can’t do that, this snippet redirects every front-end HTTP request to HTTPS from inside WordPress.
Set both addresses in Settings → General to start with https:// first. That makes WordPress create HTTPS links everywhere. This snippet then catches anyone who still arrives over HTTP.
On template_redirect, the snippet checks whether the request is already secure with is_ssl(), or whether a proxy in front of the site reports HTTPS through X-Forwarded-Proto. Trusting that header here is safe, because the worst a fake value can do is skip a redirect. If the request is plain HTTP, it redirects to the same path on HTTPS with a permanent 301.
The redirect address uses the domain from your site settings. The previous version built it from the request’s Host header, which the visitor controls, so a crafted request could redirect people to another domain. It could also redirect forever behind proxies that end HTTPS before WordPress.
The Strict-Transport-Security header tells browsers to use HTTPS automatically for a year. It’s sent only over HTTPS and doesn’t include subdomains, so a subdomain without a certificate won’t be locked out.
template_redirect. Add define( 'FORCE_SSL_ADMIN', true ); to wp-config.php for those.$_SERVER['HTTPS'] = 'on'; in wp-config.php when the forwarded protocol is HTTPS, so is_ssl() is accurate everywhere.Visit http://yoursite.com/about/. You should land on https://yoursite.com/about/. In DevTools, the first response should be a 301.