0

I am upgrading a CakePHP 1.x project to CakePHP 3.x

The 1.x project has URLs that are published in places that we can not change, like books, so I need to rewrite the previous URLs to match the Pagination URLs in CakePHP 3.x

This is an example of the 1.x URLs

http://example.org/ledgers/index/1/2
http://example.org/ledgers/index/<page_int>/<tribe_id_int>

This is what the 3.x URLs look like

http://example.org/ledgers/index?page=1&tribe=2

I have tried this htaccess ruleset

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    RewriteRule ^ledgers/index/(\d)+/(\d)+$ /ledgers/index?page=$1&tribe=$2 [NC]
</IfModule>

And the output from

die(print_r($this->request->getQueryParams(), true));

is

Array()

I saw in another StackOverflow post to try and use

https://www.generateit.net/mod-rewrite/index.php

Which gave me

RewriteRule ^ledgers/index/([^/]*)/([^/]*)$ /ledgers/index?page=$1&tribe=$2 [L]

but still the output from

die(print_r($this->request->getQueryParams(), true));

is

Array()

Any ideas on how I can get this to work?

Jeffrey L. Roberts
  • 2,485
  • 5
  • 29
  • 54

1 Answers1

1

Your rule must be defined before the ^ index.php [L] one, as it catches everything and your rule will never be reached. Specifically in your case, it must be placed even before the RewriteCond line, as conditions can only apply to a single rule. Look into using skipping rules for a workaround.

And while rewriting the URL internally will work, ie you will be able to access the query parameters, leaving the URL unchanged may have negative side effects, for example Router::url() would produce:

/ledgers/index/1/2?page=1&tribe=2

instead of:

/ledgers/index?page=1&tribe=2

So you may want to consider issuing an actual redirect like this (note the optional closing slash, and the + inside the parentheses to match the whole number, not just the last digit):

RewriteRule ^ledgers/index/(\d+)/(\d+)/?$ /ledgers/index?page=$1&tribe=$2 [NC,L,QSA,R=301]

That will externally redirect to the new URL structure, and using the QSA flag it also allows to merge in possible existing query params, ie:

/ledgers/index/1/2?foo=bar

would redirect to:

/ledgers/index?page=1&tribe=2&foo=bar

See also

ndm
  • 54,969
  • 9
  • 66
  • 105