0

My rewrite rule is currently:

rewrite ^/answer/1/(www\.)*(.)(.+)$ /answer/1/$2.html last;

So requests such as:

mydomain.co.uk/answer/1/aa
mydomain.co.uk/answer/1/www.aa
mydomain.co.uk/answer/1/www.aa/
mydomain.co.uk/answer/1/www.aa/something
mydomain.co.uk/answer/1/www.aa/something/even-deeper/and-so-on

Provides the document:

mydomain.co.uk/answer/1/a.html

Now I want to split the response so that requests such as:

mydomain.co.uk/answer/1/aa
mydomain.co.uk/answer/1/www.aa
mydomain.co.uk/answer/1/www.aa/

will provide the previous document:

mydomain.co.uk/answer/1/a.html

But requests that go any further such as:

mydomain.co.uk/answer/1/www.aa/something
mydomain.co.uk/answer/1/www.aa/something/even-deeper/and-so-on

will provide the new document:

mydomain.co.uk/answer/1/new.html

How should I change the above regex condition to accommodate the requirement?

1 Answer 1

1

I am not at home so i could not test it right now but something like this should work:

rewrite ^/answer/1/(www\.)*(.)(.+)/(.+)$ /answer/1/new.html break;
rewrite ^/answer/1/(www\.)*(.)(.+)$ /answer/1/$2.html last;

Let me explain: as stated in the nginx docs (here)

break
stops processing the current set of ngx_http_rewrite_module directives;

so if a request match the first rewrite rule (that is similar to your rewrite but ends with the /(.+) directive. This means that will match every request that was already matching but if and only if it is followed by 1 or more character after the slash. Beware of this because this means that the following url:

mydomain.co.uk/answer/1/www.aa// (yes this is a valid url)

will redirect to:

mydomain.co.uk/answer/1/new.html

if you don't want this beahaviour you can modify the regex as follow:

rewrite ^/answer/1/(www\.)*(.)(.+)/(([^/]+/?)+)$ /answer/1/new.html break;

here the (([^/]+/?)+) directive say: everything that is NOT a / repeated one or more time and that may be or not be followed by a /. all of this repeated one or more time.

I repeat, i am not able to test it right now but it should work as you expect. Remember that here the order of the rewrite url as i am testing FIRST for the url that should rewrite to mydomain.co.uk/answer/1/new.html and then there is your old rewrite that will still match the url but will not be processed by nginx since the break keyword of the previous rule.

edit: i confused last and break :)

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

1 Comment

Works but needed to change break to last (so both of them will have last) Thanks!

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.