I want to redirect all of the following types of requests to https://www.example.com
http://example.com
http://www.example.com
https://example.com
I want to redirect all of the following types of requests to https://www.example.com
http://example.com
http://www.example.com
https://example.com
This depends on how you want to redirect. You could...
Redirect from the client side. This is easy to do, simply add a script tag in the <head>
of the page HTML document that contains the following.
let excluded = ['http://www.example.com', 'https://example.com', 'http://example.com']
if (excluded.indexOf(location.origin) !== -1) {
location.href = 'https://www.example.com'
}
There is only one problem with this code, being that the browser might complain about too many redirects. The second option is safer.
If you know how, you could use .htaccess
. You will find this file in the root directory of your web server. Add the following lines:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
(Check out this question for more on this.)
If the page is not strictly static, you could redirect from the backend. There are a number of ways to do this, the most likely being to just use an npm module such as forcedomain (my personal favorite) to redirect when the request is made, rather than when the page loads. This is more efficient and the browser will not get cranky on you.
Use multiple CNAME records. If you aren't familiar with DNS, I would disregard this part of the answer. Basically, make a CNAME where the host is @
, and the value is www
. This will get all requests to the apex domain (example.com) and redirect them to the subdomain (www.example.com). When it comes to the protocol issue, there are a few ways of doing this, the best option being wildcard redirects (if your registrar provides this).
As a general rule of thumb, it's best to use DNS records, the .htaccess
file, or some sort of backend plugin if possible for redirects if you know how. This all depends on your hosting, the nature of your website (static or dynamic), and your level of knowledge on these sorts of things.
Recommend using Firebase Hosting: https://firebase.google.com/docs/hosting/quickstart