PHP preg_match page/1 in URL to redirect main URL with RegEx rules

75 Views Asked by At

I am creating php pagination and I want to matching the /page/1 in URL "/product-category/womens-jackets/page/1" If the /page/1 in matched then redirect it to the main URL "/product-category/womens-jackets" because I don't want duplicate page issue. If it is page 1 it should redirect to main URL.

Also there is RegEx rules If the page is on main URL so the rule will be below.

$product_category_rules = "/product-category/(?'shop'[\w\-]+)";

And if the URL is like "/product-category/womens-jackets/page/2" not 1 so the rule will be, For pagination.

$product_category_rules = "/product-category/(?'shop'[^/]+)/page/(?'page'\d+)";

I am just confused with the code how to conditionalize it with below condition. Also you can help me with if available any other best method to figure it out.

if(preg_match('/\/page\/[1]+\/?$/', $uri, $m))
{
    // Remove the /page/1 from url and redirect
    $redirect = preg_replace('/\/page\/[1]+\/?$/', '$1', $uri);
    header('Location: '.$root.$redirect);
    exit();
}
else
{
 
}
1

There are 1 best solutions below

0
Amir On

I just fixed the issue with match the only /page/ in URL in 2nd conduction.

// REDIRECT PAGINATION TO PAGE IF PAGINATION IS PAGE 1
if(preg_match('/\/page\/[1]+\/?$/', $uri, $m))
{
    // Remove the /page/1 from url and redirect
    $redirect = preg_replace('/\/page\/[1]+\/?$/', '$1', $uri);
    header('Location: '.$root.$redirect);
    exit();
}
elseif(preg_match('/\/page\/?/', $uri, $m)) // If matched /page/ only apply this rule.
{
    // For pagination add page/1234
    $product_category_rules = "/product-category/(?'shop'[^/]+)/page/(?'page'\d+)";
}