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.
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!
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.
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:Quick rundown:
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 oneprintf
to construct the rulesThis 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 script.sh domain.com file.txt > new_rules.txt
.Hope that this helps! Best, Bobby