Proper redirects handling

Handle as many redirects as possible outside of your application

Wether you have a mydomain.com -> www.mydomain.com redirect, or a no-ssl.com -> with-ssl.com redirect, you should do this outside of your application.

I see many bots that access all different variants, with an aggressive rate, which could further affect your server load and result in high and long peaks of traffic/load. Hundrets of requests for https://missing-www.mydomain.com/bad-or-good-url can either hit your application or be already handled by our server app.

Fortunately many websites already implement this properly, but not all. We all can do better.

If you want to redirect all http -> https traffic, you can implement this piece of nginx config:

1 server {
2     listen 80 default_server;
3     server_name _;
4     return 301 https://$host$request_uri;
5 }

If you only have one website or a few on your server, you can go with this simple config:

1 server {
2     listen 80;
3     listen 443 ssl;
4     server_name alternative-domain.com www.alternative-domain.com;
5     return 301 https://www.correct-domain.com$request_uri;
6 }

If you have a catch all server config where the server is assigned somewhere else like a gateway/reverse proxy, and you don't want to create many different server blocks, you could do it this way:

 1 server {
 2     ...
 3     if ($host ~ 'alternative-domain' ) {
 4         rewrite ^/(.*)$ https://www.correct-domain.com/$1  permanent;
 5     }
 6 
 7     if ($host ~ 'another-alternative-domain' ) {
 8         rewrite ^/(.*)$ https://www.another-correct-domain.com/$1  permanent;
 9     }
10 	...
11 }

Just make sure that you try to catch as many redirects as possible, which are not dynamic, and you should be fine. Just another small step in reducing traffic and load on your application.