I am currently using openresty nginx to proxy requests to an origin. I want to escape any unsafe characters in the uri of the request.
Basically, I am looking for a lua equivalent for the encodeURI() javascript function.
Is there a method in Lua, similar to encodeURI() in JS?
I have looked at ngx.escape_uri, but this function only escapes a URI component.
I want the uri /test/[hello] to become /test/%5Bhello%5D after encoding the URI.
If I do encodeURI("/test/[hello]/"); in JS, I get the desired output which is /test/%5Bhello%5D.
But, in Lua, if I do ngx.escape_uri("/test/[hello]/"), I get the output as '%2Ftest%2F%5Bhello%5D'.
ngx.escape_urihas an option to escape a full URI:Nonetheless,
ngx.escape_uri(str, 0)is still not the same asencodeURI.Fortunately, it's easy to write your own function that produce exactly the same output as
encodeURI:The
encode_urifunction escapes all characters except:as it described here.