This is a quick article explaining how I fixed a problem I was having with some redirections to my site not working properly.
The problem was that, when someone typed in http://www.littlebigtech.net
or www.littlebigtech.net
, the website was not served, and instead a 404 error returned. I wanted to redirect this traffic to my website.
I also did not want to interfere with my https configuration, since that was working properly.
The solution to this is rather simple if you are using NGINX.
You need to add a server block before your other server blocks in your nginx config file, which will catch the request if it contains a prepending www and modify it accordingly.
In my case the code looked like this:
server {
server_name www.littlebigtech.net;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 $scheme://littlebigtech.net$request_uri;
}
server {
server_name littlebigtech littlebigtech.net;
#rest of the configs
}
server{
if ($host = littlebigtech.net) {
return 301 https://$host$request_uri;
} # managed by Certbot
#Rest of the https configs
}
The first block will catch any request containing the www.
and respond with a 301 http code providing the stripped url, the third block will catch any http request and also respond with a 301 http code, providing the same request url but with the prepending https://
Note that here there is a double redirection case.
If the user types in http://www.littlebigtech.net
first this would be caught by the first server block, and it would change it to http://littlebigtech.net
, removing the www, but leaving the http, since we specified that the same scheme should be returned.
Hence, the user’s browser will now send a request to http://littlebigtech.net
, which will be redirected again to https://littlebigtech.net
.
To fix this, instead of keeping the same scheme in the first block, we will redirect with https:// no matter what. Hence the first server block would be:
server {
server_name www.littlebigtech.net;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 https://littlebigtech.net$request_uri;
}
Now, if I check the redirects with a website like redirect checker, I can see that typing http://www.littlebigtech.net
returns a 301 http response code and https://littlebigtech.net
as the response link. Awesome!
If you want a more complete SEO check of your site, which includes a bunch more tests, I use seobility. No affiliation, just really helpful!
If any doubts remain, check out the source for this method from this very well written stack overflow question and answer.
Hope it was helpful! Please share this on social media if you know someone that it might help! Links below!