0

i am currently moving new builds of an existing site onto a new server using nginx and have been told the URL need to direct to a new PHP file to handle how to pick out the date from a new DB.

an example incoming URL would be :

https://testsite.com/test-account-here-ABC-123456.html

This is to be caught by nginx and redirected to

https://testsite.com/profiles.php

where the file will do its bit and extract the url to get its details and do its search.

I've set up a redirect on the premise the $request_uri finds **-ABC-* within the url like so :

if ($request_uri ~ ^/(.*)-ABC-)
{
    return 302 $scheme://testsite.com/profile.php;
}

which successfully goes to that PHP file but i need to be able to extract the numbers from the URL (123456) so i can access them via query string in the PHP file, i've tried to user

return 302 $scheme://testsite.com/profile.php?url=$request_uri;

but that returns the full url which causes a infinite redirect loop and the browser to error.

Is there anyway you can extract parts of a $request_uri to then re-use in the redirect?

Something along the lines of

return 302 $scheme://testsite.com/profile.php?url=$variable1;
Jimjebus
  • 3
  • 1
  • 3

1 Answers1

0

If the numbers are always before the .html suffix, you can use this configuration:

location ~ ^/.+-ABC-([0-9]+)\.html$ {
    return 302 $scheme://testsite.com/profile.php?url=$1;
}

Using location is the preferred way of doing these kind of things in nginx. The ~ tells nginx to use regular expression matching to find the location. The string after that and before { is the actual regular expression string.

Here we match any string which has any characters at start, followed by -ABC- and then any numbers, and then ending with .html suffix.

The numbers are captured into a variable $1, because the regular expression for that part is inside parentheses.

If you want to further elaborate on the regular expression, there are plenty of regular expression tools online where you can test your modifications.

Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58