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:

server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

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

server {
    listen 80;
    listen 443 ssl;
    server_name alternative-domain.com www.alternative-domain.com;
    return 301 https://www.correct-domain.com$request_uri;
}

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:

server {
    ...
    if ($host ~ 'alternative-domain' ) {
        rewrite ^/(.*)$ https://www.correct-domain.com/$1  permanent;
    }

    if ($host ~ 'another-alternative-domain' ) {
        rewrite ^/(.*)$ https://www.another-correct-domain.com/$1  permanent;
    }
	...
}

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.