Redirect users to https protocol using .htaccess

Category: Web hosting

Force HTTPS using .htaccess

Your visitors should enter the site securely through an encrypted connection with an SSL certificate. It is a good practice, it helps positioning in Google and, above all, improves security. However, having an SSL certificate does not guarantee that they log in with HTTPS: they can connect via HTTP and not encrypt the session. To force all connections to the secure protocol, a directive must be configured in the .htaccess file.

At NubeHost we offer free SSL certificates on all web hosting accounts.

Not a customer yet? Check out our hosting plans with SSL certificate included .

If you don’t already have a .htaccess file (the name includes the dot), create it under /public_html with any text editor. The redirection is achieved with the following code within the .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Note: If your site is based on WordPress, it is easier to use a plugin like Really Simple SSL .

Redirect HTTPS only on certain domain

If you only want to force HTTPS on one of your domains, you can use the following code:

RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

Make sure you change the “example.com” domain to your own.

If this doesn’t work, try removing the first two lines:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

Redirect HTTPS for specific directories

If you only want to force the secure HTTPS protocol in the sensitive directories of your website, you can put the .htaccess file directly in that or those directories and add the following code:

RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} tudirectorio
RewriteRule ^(.*)$ https://www.example.com/tudirectorio/$1 [R=301,L]

Make sure to change the domain text to yours and “tudirectorio” to your directory name.

Ready! When you visit any web page in your account, it should redirect to the secure protocol automatically.

Still need help?

If this guide didn’t solve your issue, our team can help you via ticket.