Nginx pagination with variables rewrite

nginxrewrite

I'm using wordpress and I got this code working to get and paginate subcategories of a specific category.

It works (almost) fine because it creates me two problems that can be solved on nginx.

The first problem with this pagination:

The way the pagination is working creates a duplicate content issue by paginating two times the first page with two different urls;

  • domain.com/cat-variable-name/
  • domain.com/cat-variable-name/?cpage=1

When someone returns to "?cpage=1", it should be redirected to:

domain.com/cat-variable-name/

The second problem:

These are not SEO friendly URL's and I do have a custom permalinks with /%postname%/ but it does not rewrite this custom pagination and I have no clue on how to it without breaking anything else on my site. So…

After page one domain.com/cat-variable-name/?cpage=(page_number)

I need to find a way to rewrite all of to something like this:

domain.com/cat-variable-name/cpage/(page_number)

How can I do this?

These are the ones that I tried and failed:

I already tried these without success:

rewrite ^/?cpage=$1 /cpage/([^/]*)/;

if ($request_uri ~* ^(.+)\?cpage=1$) { 
set $dom_prefix $1; set $args ''; rewrite ^(.*)$ $scheme://$host$dom_prefix permanent; break; } 
if ($request_uri ~* ^(.+)\?cpage=(\d+)$) { 
set $dom_prefix $1; set $cpage $2; set $args ''; rewrite ^(.*)$ $scheme://$host$dom_prefix/p$cpage permanent; break; }

Note: Please keep in mind that "cat-variable-name" and "page_number" never are the same.

Best Answer

nginx $request_uri does not contain query arguments, it only contains the URI. Query argumants are available in $arg_name variables.

You can try this:

if ($arg_cpage = 1) {
    return 301 $scheme://$host$uri;
    break;
}

if ($arg_cpage ~ ^(\d+)$) {
    return 301 $scheme://$host$uri/p$1;
    break;
}