Redirect requests to another site using Nginx

Redirect requests to another site using Nginx

I recently moved my site from GitHub Pages to my own server.
For the last couple of years, I had been hosting my domain asad.pw and www.asad.pw on GitHub pages, and that included my GitHub project sites HeadlessBrowsers and Awesome-Postgres.

So far, I had been hosting the GitHub pages for these projects on my own domain name, but post the move that was no longer possible.
However, as these projects are fairly popular, a lot of people have been linking to the sites, and I am absolutely not a fan of link rot. So to preserve the links, I have set up redirects using Nginx.

Here's how:

In my site configuration files in the /etc/nginx/sites-enabled folder, I added these location blocks:

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

    server_name asad.pw;

    location ~* ^/HeadlessBrowsers {
        return 302 https://dhamaniasad.github.io/HeadlessBrowsers;
    }

    location ~* ^/awesome-postgres {
        return 302 https://dhamaniasad.github.io/awesome-postgres;
    }
}

And I did this for the site configuration files listening on port 443 (SSL), and on the naked domain (asad.pw) and the www domain (www.asad.pw).

The location ~* ^ part in the location block is important, as it sets up a case-insensitive regex search. So Awesome-Postgres, awesome-postgres, or AWESOME-POSTGRES will all redirect to the correct URL. And we also preserve any query parameters, URL fragments (#something), and URL paths (/123/456).

And now the links are working just as before!