I’m new to nginx and need to setup some redirects, I know the redirects in Nginx are regex based, however that is not my strong suit either.
We are launching our latest code, and what to redirect all instance of the following
https://uat1.lipsum.com/browse
https://uat1.lipsum.com/popular
uat1.lipsum.com/browse/[anything]
uat1.lipsum.com/popular/[anything]
TO…
https://uat1.lipsum.com/discovery
https://uat1.lipsum.com/discovery
uat1.lipsum.com/discovery/[anything]
uat1.lipsum.com/discovery/[anything]
Basically, replacing all occurrences of “browse” and “popular” with “discovery”
I tried a couple methods…
The best I could come up with was the following, which would redirect properly, but the other formats would not.
https://uat1.lipsum.com/browse
https://uat1.lipsum.com/popular
nginx.conf
location /browse/ {
rewrite ^(.*)/browse/(.*)$ /discover/ permanent;
}
location /browse {
rewrite ^(.*)/browse /discover permanent;
}
location /popular/ {
rewrite ^/popular/ /discover/ permanent;
}
location /popular {
rewrite ^/popular /discover permanent;
}
}
Use the magic of backreferences. Putting a regular expression in ()s captures the matched expression, and then using $1, $2, $3, etc will pull the first, second, third, etc captured text.
See here for more information.