0

In the nginx config file for my server, I have written the following location block:

location ~ /page/(?!(3/?|5/?|6/?|8/?)) {
    return 301 https://anothersite.com/page$is_args$args;
}

With this, I'm trying to redirect all /page/ EXCEPT the following:

/page/3
/page/3/
/page/5
/page/5/
/page/6
/page/6/
/page/8
/page/8/

Which works well for those pages. However, this also excludes any pages that START with the pattern. So pages like the following

/page/33
/page/814
/page/577

do not get redirected, but they should be. How should I change that regex so that I can limit the match only to the first character after /page/ (with or without a trailing slash)?

I've also tried this:

location ~ "/page/(?!([3]{1}/?|[5]{1}/?|[6]{1}/?|[8]{1}/?))" {
    return 301 https://anothersite.com/page$is_args$args;
}

However this seems to behave exactly like the first pattern.

Any help is much appreciated! Thanks in advance!

Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58
vascaino
  • 1
  • 2
  • You should play with any online regex tool to find out the proper regex you want to use. On them, you can enter sample strings, your rules, and the page will show you how they are matched. Just Google for "regex validation tool", and you will find many. – Tero Kilkanen Dec 10 '17 at 11:28
  • Thanks man, but I indeed have done that. Unfortunately I still haven't been able to figure this one out. While I can do some regex it's just not my forte. – vascaino Dec 10 '17 at 15:27

2 Answers2

0

You need to match the end of the string with $. This means that strings that continue beyond that point will not match the regular expression.

For instance:

location ~ /page/(?!(3/?|5/?|6/?|8/?))$ {
Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
  • Thanks for getting back on this mate, but your suggestion doesn't seem to be working for me. When I tried that, no /page/ get redirected at all. I'm using nginx 1.10.1 if this is relevant. – vascaino Dec 09 '17 at 17:48
0

Unfortunately I wasn't able to get that one figured out. I ended up doing this:

location /page/ { return 301 https://anothersite.com/page$is_args$args; } location ~ ^/page/3/?$ {} location ~ ^/page/5/?$ {} location ~ ^/page/6/?$ {} location ~ ^/page/8/?$ {}

This does the job, although it's not a one-liner as I was hoping.

vascaino
  • 1
  • 2