NGINX rewrite script

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$ permanent;
rewrite ^/oldpage$ permanent;
rewrite ^/error.php$ permanent;

For now, my script looks like this:

if [ "$#" -eq 0 ]; then
    echo "Usage: ./ <domain> <file>"

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 “$” in the beginning of the new address.

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Accepted Answer

Hi there,

There are probably multiple ways to do it, but I would personally use a for loop to loop through each of the lines fo the file and then use printf to construct the redirect rule as follows:


if [ "$#" -eq 0 ]; then
    echo "Usage: ./ <domain> <file>"

IFS=$'\n' # bash specific
for line in $(cat ${FILE})
    old=$(echo $line | awk '{print $1}')
    new=$(echo $line | awk '{print $2}')
    printf "rewrite ^/%s$ https://${DOMAIN}/%s permanent;\n" "$old" "$new"


Quick rundown:

  • It sets the IFS (Internal field separator) variable as separators so that the for loop would go through each separate line
  • Then we start the for loop
  • Using awk we get the old and the new URLs as we follow the conversion that the first one is the old URL and the second is the new one
  • Finally, we use the printf to construct the rules

This will print the results on the screen and you can copy them from there. Or alternatively, when running the script you could send the STDOUT to a file: bash file.txt > new_rules.txt.

Hope that this helps! Best, Bobby

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.