I set up the SSL and custom domain name for my website on the App Engine.
It works perfectly fine: I can go to https://www.mywebsite.com and the page loads.
But I would like to make the following change.
If I go to mywebsite.com, I would to be redirected immediately to https://www.mywebsite.com .
How can I do that ?
if you are using expressjs then this code below will do it.
app.get('*', function (req, res, next) {
var checkHost = req.get('host').substring(0, 4);
var condition = req.get('x-forwarded-proto') !== "https" || checkHost !== 'www.' || ( req.get('host').indexOf('www.') < 0);
if (condition) {
res.set('x-forwarded-proto', 'https');
if (checkHost === 'www.' && ( req.get('host').indexOf('www.') >= 0)) {
res.redirect('https://' + req.get('host') + req.url);
}
else {
res.redirect('https://www.' + req.get('host') + req.url);
}
} else {
next();
}
});
You can put this before you start adding routes. It will inspect the protocol of each request and redirect to the https version if it is coming in over http
app.use(function(req, res, next) {
if (req.protocol === 'http') {
var host = req.host.replace('www.', '');
return res.redirect('https://www.' + host + req.originalUrl);
}
next();
});
Note that if nginx/apache is handling the https stuff and forwarding to a non-https node server this will not suffice. You will need to look at headers in your conditional rather than req.protocol
(something like the conditional that @Asif has)
You need to create .htaccess file at root of your server for redirect.
.htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.urserver.com/folder/$1 [R,L]
</IfModule>
using upper you can redirect to your domain
You could also map your naked domain mywebsite.com
to your GAE app, in addition to your www.mywebsite.com
. Basically by repeating the procedure for Adding a custom domain for your application and selecting the naked domain at step 4 (emphasis mine):
Continue to the next step of the Add new custom domain form and
select the custom domain you want to point to your App Engine app:
Specify the domain and subdomains you want to map.
Note: The naked domain and www subdomain are prepopulated in
the form.
- A naked domain, such as
example.com
, maps to http://example.com
.
- A subdomain, such as
www
, maps to http://www.example.com
.
Click Submit mappings to create the desired mapping.
Pros:
- simpler
- works for both standard and flex env apps, regardless of the app's language
- works for static content as well, unlike solutions based on app code changes
Cons: