How to redirect http to https and https://www to https://?

by raphael_tillman , in category: Third Party Scripts , a month ago

How to redirect http to https and https://www to https://?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , a month ago

@raphael_tillman 

To redirect HTTP to HTTPS and also remove the 'www' subdomain, you can make use of a combination of server configuration and a .htaccess file. Below are the steps to achieve this:

  1. Modify the server configuration:
  • If you are using Apache web server, you can add the following lines to the VirtualHost configuration file for your website:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html/example
    SSLEngine on
    SSLCertificateFile /path/to/certificate.crt
    SSLCertificateKeyFile /path/to/private.key
</VirtualHost>


This configuration will redirect all traffic coming to http://www.example.com to https://example.com.

  1. Create a .htaccess file:
  • You can also create a .htaccess file in the root directory of your website with the following content to handle the redirection:
1
2
3
4
5
6
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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


This .htaccess file will redirect all HTTP traffic to HTTPS and also remove the 'www' subdomain.


Make sure to replace example.com with your actual domain name in the above configurations. Also, remember to test the redirection to ensure it is working correctly.