proxy_redirect ~*http://127.0.0.1:3000(/.*)$ http://www.example.com$1;
This is an example of proxy_redirect
modifying a redirect URL by matching the URL with a regular expression, but where the "/
" and ".
" characters are not added as escaped characters.
I learned from this article at https://www.nginx.com/blog/regular-expression-tester-nginx/ that characters like "/
" can be used without the escape character, so ".
" character needs to be escaped?
Maybe the following example is the correct syntax?
proxy_redirect ~*http://127\.0\.0\.1:3000(/.*)$ http://www.example.com$1;
CodePudding user response:
Yes, since the first regex pattern does not escape dots, they works as a wildcards matching any character (including dot character itself). For the real use case it won't cause any problems since it perfectly matches http://127.0.0.1:3000/...
and you don't expect some weird output from your backend (at least most of the time :)). However your second pattern technically more correct (and I think it also slightly more performant since it uses less wildcards).
The slash character commonly used in many programming languages as the regex pattern start/stop delimiter, so most online regex testers expects you to escape it in your patterns by default. However nginx uses its own ~
(for case-sensitive matching) or ~*
(for case-insensitive matching) pattern prefixes. In a pattern itself slash character does not have any special meaning, so I think it was a purposeful (and handy) nginx design solution (because slashes appear so often in a real life nginx regex patterns).
On the other hand there are some cases where you should quote nginx patterns because of use of some characters that are normal in the other circumstances, for example curly braces (which would be considered as nginx control block delimiters otherwise). That is, you cannot use
proxy_redirect ~*http://127\.0\.0\.\d{1,3}:3000(/.*)$ http://www.example.com$1;
line unless you quote (both single- and double-qouting allowed) your regex pattern:
proxy_redirect "~*http://127\.0\.0\.\d{1,3}:3000(/.*)$" http://www.example.com$1;