Automate Domain Redirects with Nginx on DigitalOcean Using Taskfile

Introduction

Domain redirects are often necessary for web administrators. In this guide, we'll demonstrate how to set up a domain redirect with Nginx on a DigitalOcean droplet and automate the process using Taskfile. By the end of this tutorial, you'll be able to redirect http://example.com to http://www.example.com (substitute your actual domain names).

This guide is a follow up of a previous article where I went through the process manually. You can read it here.

Prerequisites

  1. A registered domain name
  2. A DigitalOcean account
  3. A DigitalOcean droplet (we'll create one during this tutorial)
  4. doctl - the DigitalOcean cli - installed and authenticated on your local machine
  5. task (Taskfile's command-line tool) installed on your local machine
  6. SSH access to your server

Step 1: Create a DigitalOcean Droplet

Create a new droplet on DigitalOcean with the lowest possible cost in the fra1 region. You can do this through the DigitalOcean dashboard or by using doctl on your local machine. For this tutorial, we'll use doctl.

doctl compute droplet create <your_droplet_name> --image ubuntu-23-04-x64 --size s-1vcpu-512mb-10gb --region fra1 --ssh-keys <your_ssh_key_fingerprint> --wait

Replace your_droplet_name with the droplet name (also in Taskfile.yml) of your choice and replace your_ssh_key_id with your actual SSH key ID, which you can obtain by running doctl compute ssh-key list.

Step 2: Create a Taskfile to automate the setup

Create a Taskfile.yml in your project directory and add the following tasks to automate the process of setting up the redirect. These tasks are largely self-explanatory.

#
# https://taskfile.dev/
#
# Install task: 'brew install go-task'
#
# Usage:
#
# -  run 'task create-droplet' to create the DigitalOcean droplet
# -  run 'task setup-redirect' to setup the nginx redirect and verify it's working
#
# Requires a DNS A record for all Domains to be redirected pointing to the droplet's IP address
#

version: '3'

env:
  DROPLET_NAME: '{{default "your-droplet-name" .DROPLET_NAME}}'
  SERVER_USER: '{{default "root" .SERVER_USER}}'
  SERVER_IP: '{{.SERVER_IP}}'
  SOURCE_DOMAIN: '{{default "example.com" .SOURCE_DOMAIN}}'

tasks:
  fetch-server-ip:
    desc: Fetch the server IP address using doctl and set it as an environment variable
    cmds:
      - doctl compute droplet get {{.DROPLET_NAME}} --format "PublicIPv4" --no-header

  # Create digitalocean droplet via doctl
  # create-droplet:
  #   desc: Create a DigitalOcean droplet in the fra1 region
  #   cmds:
  #     - doctl compute droplet create {{.DROPLET_NAME}} --image ubuntu-23-04-x64 --size s-1vcpu-512mb-10gb --region fra1 --ssh-keys <your_ssh_key_fingerprint> --wait

  install-nginx:
    desc: Install Nginx on the remote server
    cmds:
      - ssh "{{.SERVER_USER}}@{{.SERVER_IP}}" "apt update"
      - ssh "{{.SERVER_USER}}@{{.SERVER_IP}}" "apt install -y nginx"

  copy-config:
    desc: Copy the Nginx redirect configuration file to the server
    cmds:
      - scp nginx-redirect.conf "{{.SERVER_USER}}@{{.SERVER_IP}}:/etc/nginx/sites-available/botzenhart-io"

  configure-redirect:
    desc: Configure the Nginx redirect
    cmds:
      - ssh "{{.SERVER_USER}}@{{.SERVER_IP}}" "ln -sf /etc/nginx/sites-available/botzenhart-io /etc/nginx/sites-enabled/"

  check-config:
    desc: Check Nginx configuration
    cmds:
      - ssh "{{.SERVER_USER}}@{{.SERVER_IP}}" "nginx -t"

  restart-nginx:
    desc: Restart Nginx
    cmds:
      - ssh "{{.SERVER_USER}}@{{.SERVER_IP}}" "systemctl restart nginx"

  verify-redirect:
    desc: Verify the redirect is working as expected
    cmds:
      - 'response_code=$(curl -s -o /dev/null -w "%{http_code}" -I http://{{.SOURCE_DOMAIN}}); if [ "$response_code" = "301" ]; then echo "Redirect is working!"; else echo "Redirect is NOT working. Response code: $response_code"; fi'

  setup-redirect:
    desc: Setup and verify the Nginx redirect
    cmds:
      - task: install-nginx
      - task: copy-config
      - task: configure-redirect
      - task: check-config
      - task: restart-nginx
      - task: verify-redirect

Step 3: Create the Nginx configuration file

Create a nginx_redirect.conf file in your project directory with the following configuration:

server {
    server_name _;
    return 301 https://www.example.com;
}

Replace example.com with your actual domain names.

This configuration will redirect any incoming request to https://www.example.com. If you want to set up different redirect destinations for incoming requests, adjust the configuration as follows:

server {
    server_name example.com;
    return 301 https://www.example.com;
}

Add one server block for each address you want to redirect.

Step 4: Create a bin wrapper for the task execution

Create a setup-redirect-service shell script to fetch the server's IP address using doctl, export the IP as an environment variable for task execution:

#!/bin/bash

droplet_name=<YOUR DROPLET NAME>

# Fetch the server IP address using doctl
echo "Fetching server ip ..."
SERVER_IP=$(task fetch-server-ip)

# Export the SERVER_IP environment variable
echo "Exporting SERVER_IP for use in other tasks ..."
export SERVER_IP

# Run the Taskfile setup-redirect task with the SERVER_IP variable
task setup-redirect

Make the script executable:

chmod +x setup-redirect-service

Step 5: Set up the redirect service

Run the setup-redirect-service script to set up the redirect service:

./bin/setup-redirect-service

This script fetches the server's IP address based on the DigitalOcean droplet name, sets it as an environment variable, and then runs the setup-redirect tasks.

Wrapping it up

In this guide, I've shown how to set up a domain redirect using Nginx on a DigitalOcean droplet and automate the process with Taskfile. This approach simplifies domain redirect management and can be easily applied to other projects with minimal effort.

By automating the process, you create an easy-to-follow, repeatable, and deterministic process, while also documenting the steps as executable code.

I hope you found this tutorial helpful, and that it will make managing domain redirects a breeze in your future projects.

Happy redirecting, and see you next time! 👋