JRehkemper.de

Create NGINX-Container to redirect domain to another (HTTP 301)

If you want to redirect one domain to another, but your registrar does not provide a solution for that, you can spin up a small NGINX container to do just that.

I will not cover how to install Docker and Docker-Compose in this post.

Docker-Compose file

Default

The docker-compose.yml should look like this.

version: "3"
services:
  nginx-redirect:
    image: nginx
    container_name: nginx-redirect
    volumes:
      - ./config/default.conf:/etc/nginx/conf.d/default.conf
    networks:
      - net
    restart: unless-stopped
    ports:
      - 80:80

With Traefik

If you use traefik, you can take this as an example, but you will probably need to change the network name. Mine is called net.

version: "3"
services:
  nginx-redirect:
    image: nginx
    container_name: nginx-redirect
    volumes:
      - ./config/default.conf:/etc/nginx/conf.d/default.conf
    networks:
      - net
    restart: unless-stopped
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.nginx-redirect.rule=Host(`blog.jrehkemper.de`)"
      - "traefik.http.routers.nginx-redirect.entrypoints=https"
      - "traefik.http.routers.nginx-redirect.tls=true"
      - "traefik.http.routers.nginx-redirect.tls.certresolver=production"
      - "traefik.docker.network=net"

networks:
  net:
    name: net
    external: true

NGINX-Config

Now we need to configure the nginx-server to redirect requests. In the compose file we already mounted the file ./config/default.conf into the container. Now we need to create the default.conf file.

server {
  listen 80;
  server_name blog.jrehkemper.de;
  return 301 $scheme://jrehkemper.de$request_uri;
}

In this example I will redirect from blog.jrehkemper.de to jrehkemper.de, but you can use every other domain as well.

$scheme contains if the request was http or https.
$request_uri contains the path behind the domain.
You can omit them if you want to.

Start the Container

Finally we need to start the container.

[tux@server]$ docker-compose up -d

Now the redirect should work as expected.

profile picture of the author

Jannik Rehkemper

I'm an professional Linux Administrator and Hobby Programmer. My training as an IT-Professional started in 2019 and ended in 2022. Since 2023 I'm working as an Linux Administrator.