Search code examples
apache.htaccessmod-rewriteurl-rewritingquery-string

Rewrite URL where one variable is changing


I am trying to get below .htaccess rewrite working where the page=1 can have any numeric value

RewriteCond %{QUERY_STRING} ^per_page\=10&page\=1&_embed&categories\=&categories_exclude\=31,32,92$
RewriteRule ^wp\-json/wp/v2/posts$ /wp-json/wp/v2/posts?per_page=10&page=1&_embed&categories_exclude=31,32,92 [L]

So if the variable id page=6 it stays that way.

Any suggestions?


Solution

  • Capture the value of the page URL parameter in the RewriteCond regex (CondPattern) and use a corresponding %<number> backreference in the substitution string. For example:

    RewriteCond %{QUERY_STRING} ^per_page=10&page=(\d+)&_embed&categories=&categories_exclude=31,32,92$
    RewriteRule ^wp-json/wp/v2/posts$ /wp-json/wp/v2/posts?per_page=10&page=%1&_embed&categories_exclude=31,32,92 [L]
    

    The regex \d is a shorthand character class for digits and is equivalent to the long-hand [0-9].

    The %1 backreference contains the string captured by the first capturing subgroup, (\d+), in the preceding CondPattern (ie. the value of the page URL parameter).

    Aside: No need to backslash-escape = and - in the regex as they carry no special meaning in the context they are being used here.

    Reference:


    However, you might as well capture "everything" and save repetition, "simplifying" the substitution string. For example:

    RewriteCond %{QUERY_STRING} ^(per_page=10&page=\d+&_embed)&categories=(&categories_exclude=31,32,92)$
    RewriteRule ^wp-json/wp/v2/posts$ /$0?%1%2 [L]
    

    Here, we capture the part of the query string before and after the &categories= URL parameter (the section to be removed). These are saved in the %1 and %2 backreferences respectively.

    The $0 backreference contains the URL-path matched by the entire RewriteRule pattern.