nginx Regex Tester
I do not like editing nginx regexes directly in production config. A small mistake in a location or rewrite rule can send the wrong traffic to the wrong place.
I test the pattern first, then put it into nginx.
nginx regex locations
nginx has a few location forms. The two regex forms I use are:
location ~ ^/articles/(.+)/$ {
# case-sensitive regex match
}
location ~* \.(png|jpg|jpeg|gif|webp)$ {
# case-insensitive regex match
}
The important bits:
~is case-sensitive.~*is case-insensitive.- Captures are available as
$1,$2, and so on. - nginx chooses locations with its own matching rules. Prefix locations matter, and regex locations are tested in order when nginx gets to that step.
That last part is where testing the regex alone is not enough. I still test nginx config with nginx. But testing the expression first catches most of the obvious mistakes.
Test the path, not the full URL
For nginx location blocks, I usually test the path:
/articles/regex-macos-tutorial/
/articles/swift-regex-builder/
/regex/
/images/regex/device.png
Then I write a pattern:
^/articles/([^/]+)/$
This captures:
regex-macos-tutorial
swift-regex-builder
It does not match:
/regex/
/images/regex/device.png
That is the kind of quick check I want before touching a config file.
Test rewrite captures
For a routing rule, I test the capture groups before I write the nginx rule.
Pattern:
^/old/articles/(.+)/$
Replacement target:
/articles/$1/
nginx rule:
rewrite ^/old/articles/(.+)/$ /articles/$1/ permanent;
If the regex tester shows the capture includes a trailing slash I did not expect, I fix it before it becomes a rewrite bug.
Check nginx syntax too
After editing config, I still run:
nginx -t
or, inside Docker:
docker exec nginx nginx -t
The regex tester checks the expression. nginx -t checks whether nginx accepts the config. I want both.
Where Regex for macOS fits
Regex for macOS is useful for the first pass: sample paths on one side, pattern on the other, matches and capture groups visible while I edit.
Then I move the pattern into nginx config and test the config normally.
Related: Regex tester for macOS and regex performance tester.