php.htaccessmod-rewritesslhttps

Force SSL/https using .htaccess and mod_rewrite


How can I force to SSL/https using .htaccess and mod_rewrite page specific in PHP.


Solution

  • For Apache, you can use mod_ssl to force SSL with the SSLRequireSSL Directive:

    This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL.

    This will not do a redirect to https though. To redirect, try the following with mod_rewrite in your .htaccess file

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    

    or any of the various approaches given at

    You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)

    if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
        if(!headers_sent()) {
            header("Status: 301 Moved Permanently");
            header(sprintf(
                'Location: https://%s%s',
                $_SERVER['HTTP_HOST'],
                $_SERVER['REQUEST_URI']
            ));
            exit();
        }
    }