3

I am trying to rewrite the following url in NGINX:

https://example.com/ab12-cdef4567?c=123

Into this:

https://example.com/ab12-cdef4567.php?c=123

The pattern will always be {4 alphanumeric}-{8 alphanumeric}

This is what I am attempting without success:

rewrite ^/(.{4}-.{8})?(.*)$ /$1.php?$2 last;
1
  • Does any of the below answers help? Please do let me know if you need something else in regards to this post. Commented Jun 27, 2020 at 5:57

2 Answers 2

5

You may try:

^(.*)(\w{4}-\w{8})(.*)$

Explanation of the above regex:

  • ^, $ - Represents start and end of line respectively.
  • (.*) - Represents first capturing group matching everything before alphanumeric pattern string.
  • (\w{4}-\w{8}) - Represents second capturing group matching the required alphnumeric pattern. If you do not want to include _ then you can assign them manually; something like [0-9A-Za-z].
  • (.*) - Represents third capturing group matching everything after alphanumeric pattern string.
  • $1$2.php$3 - For the replacement part; you can use the first, second and 3rd capturing group along with .php extension.

Pictorial Representation

You can find the demo of the above regex in here.

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

Comments

0

You cannot match the query string (?c=123) using rewrite. Nginx uses a normalised URI when matching location and rewrite statements, which has the query string removed.

The rewrite directive will append the original query string to the resulting URI unless the replacement string ends with a ?. See this document.

For example:

rewrite "^(/.{4}-.{8})$" $1.php last;

The entire regular expression needs to be in quotes because of the braces.

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.