To redirect non-HTTPS requests to HTTPS and non-www requests to www, you can use a combination of server configuration and a redirect rule.
- Server Configuration: Configure your web server to redirect all non-HTTPS requests to HTTPS. This can be done by adding a redirect rule in your server configuration file.
For example, if you are using Apache, you can add the following lines to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
These lines tell the server to:
- Turn on the rewrite engine
- Check if the request is not already using HTTPS or is not using the www subdomain
- If the condition is true, redirect the request to the HTTPS version of the URL with the www subdomain
- Redirect Rule: You can also add a redirect rule to your website’s code to ensure that all non-www requests are redirected to the www version of the site. This can be done by adding the following code to the top of your website’s .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
These lines tell the server to:
Turn on the rewrite engine
Check if the request is not already using the www subdomain
If the condition is true, redirect the request to the www version of the URL
By combining these two methods, you can ensure that all non-HTTPS requests are redirected to HTTPS and all non-www requests are redirected to the www version of your website.