How do I do a 301 redirect via Nginx?

Assuming your sites-enabled folder contains the blog.club.in.conf and blog.club.in-ssl.conf, you need to edit those files (sites-available is a list of configuration files you can use, and sites-enabled is (usually a linked list) of configuration files that will be used; by linked list, I mean when you edit something in sites-available, it will change in sites-enabled as well)! It would look something like this in the end:

(non-SSL)

server {
    listen 80;
    listen [::]:80;

    server_name <%= url %>;
    root <%= webroot %>;

    location / {
        # Force SSL and redirect
        return 301 https://blog.club.com$request_uri
    }

    location ~ /.well-known {
        # Allows SSL certificate renewal
        allow all;
    }
}

(SSL)

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name <%= url %>;
    root <%= webroot %>;

    ssl_certificate <%= fullchain %>;
    ssl_certificate_key <%= privkey %>;
    include <%= sslparams %>;

    location / {
        # Force SSL and redirect
        return 301 https://blog.club.com$request_uri
    }

    location ~ /.well-known {
        # Allow SSL certifcate renewal
        allow all;
    }
}

Note that <%= {var} %> are variables that you should see in your files

After you do that, run sudo nginx -t to make sure you didn’t break anything, and then run sudo nginx -s reload to refresh the configuration file.

1 Like