Are you struggling with Nginx rewrite rules and $ ?

less than 1 minute read

rewrite ^/that-s-my-original-uri/(with-my-folder)/(.*)$ /that-s-my-destination$$1/$2 last;

See the $$1 ?

Are you trying to use a $ in the destination of your rewrite rule ? Then you may have try escaping it, and found out you can only do it via some LUA scripting you might not want or a third party plugin that you can’t use for X or Y reason. The constant result of this situation ?

nginx: [emerg] invalid variable name in /etc/nginx/sites-enabled/XXXXXXXX:YYY

Ok so what’s next ? The idea would be to host the $ inside a variable. Sadly, the set argument does not allow this and will reject you with the same error. The solution would be to use geo in your nginx.conf and replace use the key:

geo $dollar {
	default "$";

and then

rewrite ^/that-s-my-original-uri/(with-my-folder)/(.*)$ /that-s-my-destination$dollar$1/$2 last;

And, voila !