Add to Favourites Add to Favourites    Print this Article Print this Article

Force https using an .htaccess file

If you want to force a given website or path to use https, redirected from http, you can create an .htaccess file in the DocumentRoot for that domain or hostname, and add the following code:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

which will redirect any non-https connections to https using the same request and GET variables.

If your site is running through CloudFlare, your https requests to it may actually hit your server in plaintext (http), which is confusing.
For that case, you might need something like this for an http to https redirect:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

where the only usable header is X-Forwarded-Proto, because the %{HTTPS} variable is "off" for requests from the CloudFlare network.

Globally in Apache

If you want this applies to all domains in your server, follow these instructions:
  1. Create the global file:


    and insert code:

    |*if SUB|
    |*if SSL_TEMPLATE="1"|

    This will set what we want to redirect to, and blank the redirect if it's an SSL VirtualHost
  2. Next, we want to actually use the variable, so create the file


    and add code:

    |*if SSL_REDIRECT_HOST!=""|
           Redirect / https://|SSL_REDIRECT_HOST|/

  3. If you want to disable this for any domain, go to:

    Admin Level -> Custom Httpd Config ->

    and in the CUSTOM token textarea, add this text


    which makes the variable blank, so it's not used.
  4. Lastly, rewrite the configs to use it

    cd /usr/local/directadmin/custombuild
    ./build rewrite_confs


If you're running nginx, go to:

Admin Level -> Custom Httpd Config ->

and in token |CUSTOM4|, add:

|*if SSL_TEMPLATE="0"|
       return 301 https://$host$request_uri;


For added security, you can tell all clients to always use https, even if there is an http link from somewhere.  HSTS will silently change the request to use https without needing to be asked, so at no point is http ever used (except on the first attempt, where the browse is given the header, then ever asks again).  To setup HSTS, add this to your public_html/.htaccess file:

Header set Strict-Transport-Security "max-age=31536000" env=HTTPS

Note: This means you cannot connect to http again, even if you wanted to, so usually only applies to sites that only ever use https, and never want http.

Was this answer helpful?

Also Read