1

I want to create one location regex for an endpoint that I currently serve using the following four rules.

location ~* ^/api/(?<version>.*)/(?<service>.*)(/.*/.*/.*/.*)$ {
...
}

location ~* ^/api/(?<version>.*)/(?<service>.*)(/.*/.*/.*)$ {
...
}

location ~* ^/api/(?<version>.*)/(?<service>.*)(/.*/.*)$ {
...
}

location ~* ^/api/(?<version>.*)/(?<service>.*)(/.*)$ {
...
}

That allow an access to my APIs using the following routes:

https://myapp.mydomain.com/api/v1/anyservice/foo
https://myapp.mydomain.com/api/v2/anyservice/foo/bar
https://myapp.mydomain.com/api/v1/anotherservice/foo/bar/thingy
https://myapp.mydomain.com/api/v1/anotherservice/foo/bar/thingy/owl

I have tried many solutions. For example:

location ~* "^/api/(?<version>.*)/(?<service>.*)(/.*){1,4}$" {
...
}

or

location ~* "^/api/(?<version>.*)/(?<service>.*)(/.*)*$" {
...
}

None of the solution I've tried has worked. Any idea ?

4
  • Could you make an example Commented Nov 23, 2018 at 14:02
  • The content has been edited with four examples or urls. Commented Nov 23, 2018 at 14:14
  • Does the Version (v1) or the service (anyservice) change ? Commented Nov 23, 2018 at 14:26
  • yes, it's a multi-version micro-services environment. The values of version and service are also injected into the header of the requests. Commented Nov 23, 2018 at 14:29

2 Answers 2

4

You can use this regex to achive your goal:

/api/(?<version>[^/]+)/(?<service>[^/]+)(?:/[^/]+){1,4}$

You must set the 'multiline' option if your text contains more than one line (like in exmaple above).

The regex starts matching '/api/' (Note the '^' symbol you had is removed, since it's not start of line).

Then it creates a named Group 'version' that matches any characters not being a slash, then a slash and a new named Group 'service. Again it matches any character not being a slash.

Then it creates a non capturing Group, matching a slash followed by any characters not being a slash. This Group is matched from 1 to 4 times.

Edit:

To match the path in a Group, I have changed to include a named Group called 'path':

/api/(?<version>[^/]+)/(?<service>[^/]+)(?<path>(?:/[^/]+){1,4})$

Now you get the path in the 'path' Group.

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution works perfectly ! Note that you have to put some the regex between quotes because of {.
1

I don't know if i understood your question correctly but this RegEx might solve it.

.*\/api\/(v\d)\/(.+service)(\/.+\/?)*

It matches every given example.

In Group 1 it captures the Version.

In Group 2 it captures the Service.

In Group 3 it captures the /foo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.