Score:1

Nginx location matching with regex year/month/day/*

fm flag

I have some old url pattern to redirect to new location in nginx.

A typical clean url looks like example.com/2021/06/13/78676.html?..

Im roughly trying to match number of digit in each block like:

location ~ "^[0-9]{4}/[0-9]{2}/[0-9]{2}/([0-9]+).html" {
   rewrite ^ /archive.php?q=$1;
}

Where exactly Im going wrong please..

Michael Hampton avatar
cz flag
What is the problem you are having?
TELA avatar
fm flag
Oops! forgive me. I forgot to comment out Certbot's 'return 404' directive at the end of file. I was applying this redirection for non https pages. everything works fine. Thank you
Score:2
jp flag

The first issue is that all Nginx URIs begin with a leading /. So your regular expression will never match.

The second issue is that numeric captures are overwritten whenever a new regular expression is evaluated. So in your configuration, $1 will always be empty.

You could use a named capture:

location ~ "^/[0-9]{4}/[0-9]{2}/[0-9]{2}/(?<value>[0-9]+)\.html" {
    rewrite ^ /archive.php?q=$value last;
}

Alternatively, place the numeric capture in the rewrite statement:

rewrite "^/[0-9]{4}/[0-9]{2}/[0-9]{2}/(?<value>[0-9]+)\.html" /archive.php?q=$1 last;

Or use a try_files statement instead of rewrite:

location ~ "^/[0-9]{4}/[0-9]{2}/[0-9]{2}/([0-9]+)\.html" {
    try_files nonexistent /archive.php?q=$1;
}
TELA avatar
fm flag
I found there is an issue with named capture too if someone pass a GET variable 'q' along with the request url like /2021/06/13/78676.html?a=1&q=asdf . In that case even named value seems overwritten by new $q = asdf. Any workaround ?
Richard Smith avatar
jp flag
If you want to keep the other parameters (like `a=1`) it gets tricky. Otherwise, use a trailing `?` in the replacement value in the `rewrite` statement and the original arguments will **not** be appended. For example: `rewrite ^ /archive.php?q=$value? last;` - see [this document](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite).
do flag
Btw repeating a point discussed elsewhere, ensure you use double quotes on such regex strings that contain curly brackets otherwise it will not work... also there should be no need to end the string with any `$` sign either.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.