简体   繁体   中英

How to use RegExp in a location path on my nginx config?

I have a navigation route that looks like:

/book/bookname-1234/

I have an API route to purchase the book at:

/book/1234/purchase

For the navigation route, I want my Nextjs server to handle it, but the API route I want be handled by our python server.

In my nginx config I have defined Nextjs routes with the catchall going to python.

For the navigation route, I have it set as:

location ~ /book/^[a-z]+(?:-[0-9]+)$ {
   try_files $uri @nextjs;
}

I have also tried putting double quotes around the "/book/^[az]+(?:-[0-9]+)$"

What am I doing wrong here?

To match the url, you can use:

/book/[a-z]+-[0-9]+/$

If you want to reuse the capture group values, you can use 2 capture groups.

Note that there is an ending / in the example string, and using ^ denotes the end of the string.

/book/a-z]+-[0-9]+/$

Regex demo

Then you could use the 2 capture groups followed by the word purchase to get /book/1234/purchase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM