Nginx bulk url redirect with map

Gaurav Swaroop
1 min readFeb 22, 2021

--

Setting up multiple redirects with nginx become intimidating some times, Here is a simple solution via map which can be useful to write the nginx rule in more manageable way.

This blog will use nginx base image to show the redirection , you can update as per your implementation in your organization.

Setup nginx

once you docker installed on your ubuntu/MacOS

docker run -p 80:80 -d --name nginx nginx

Create redirect map file

docker exec -it nginx /bin/bash
touch /etc/nginx/redirect/test_redirect.map

Add following content to `/etc/nginx/redirect/test_redirect.map`

map $request_uri $new_uri {
default "";
<old_url1> <new_url1>;
.
.
<old_urln> <new_urln>;
}

you can use regex also as for above list-

~^/aboutme/(.*)?$ /readmore/;

update /etc/nginx/nginx.conf

Add include of map into /etc/nginx/nginx.conf

include /etc/nginx/redirect/test_redirect.map;

Add redirects to server block

once your global nginx knows about map you can add the redirect map to server block where you want to setup the redirects

location / {
root /usr/share/nginx/html;
index index.html index.htm;
if ($new_uri != "") {
rewrite ^(.*)$ $new_uri permanent;
}
}

And all set , all your redirects will be set !!!

--

--

Gaurav Swaroop
Gaurav Swaroop

Written by Gaurav Swaroop

SRE, Cricket Lover and Wanderer

No responses yet