Report this

What is the reason for this report?

NGINX rewrite script

Posted on December 19, 2021

Hi, Sometimes I’ve to add hundreds of redirects to my NGINX server block. Such a script could definitely make my work easier. I didn’t find ready-made solutions. I’m writing a script that gets addresses from a file and creates rewrite rules for NGINX based on it. The file just contains the old address and the new address separated by a space, for example:

old.html new.html
oldpage newpage
error.php 404

So I should get something like this:

rewrite ^/old.html$ https://domain.com/new.html permanent;
rewrite ^/oldpage$ https://domain.com/newpage permanent;
rewrite ^/error.php$ https://domain.com/404 permanent;

For now, my script looks like this:

if [ "$#" -eq 0 ]; then
    echo "Usage: ./rewrite.sh <domain> <file>"
    exit
else
    DOMAIN=${1}
    FILE=${2}
fi

sed -e 's/$/ permanent;/' -i $FILE #end of each line

It does nothing but add “permanent ;” to the end of each line. How do I add “rewrite ^/” to the beginning of each line? I tried this way, but it doesn’t work :

REW=“rewrite ^/” sed -i -e “s/^/‘${REW}’/” $FILE

I also have no idea how to add “$ https://domain.com/” in the beginning of the new address.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.