3

I'm new to CakePHP. I have a website that was built by someone else in CakePHP 3.3.16. There are links to website.com/page and also website.com/page/.

What's the best way to get /page/ redirecting to /page without affecting anything else that might start with a /page/?

The route.php has this...

$routes->connect('/page/*', ['controller' => 'Page', 'action' => 'something']);

Then I have a PageController.php which has

public function something($site_id = null)
{
...
}

Will this work in the routes.php? How would I specify that this is a 301 redirect?

use Cake\Routing\RouteBuilder;
Router::scope('/', function (RouteBuilder $routes) {
      $routes->redirect('/page/','http://website.com/page');
      $routes->connect('/page/?*', ['controller' => 'Page', 'action' => 'something']);
   });

This doesn't seem to work in the .htaccess (/page/ is displayed and not redirected)...

Redirect 301 /page/ http://website.com/page
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

sdexp
  • 756
  • 4
  • 18
  • 36

1 Answers1

1

as a first glimpse to fix this would be instead of putting the Route::scope would be Router::connect and Router::redirect imo. Therefore, an approach to a solution would be first doing something like this.

 Router::connect('/page/*', ['controller' => 'Page', 'action' => 'something']);

And then you redirect the page with the cake command redirect:

 Router::redirect('/page/','/page', array('status' => 301));

In the project that I use which is CakePhp 2.6, I always have redirected pages like this depending on the task. Sometimes you can do this type of redirects inside the Controller but it is best to avoid it for not mixing routing with programming logic.

Oris Sin
  • 1,023
  • 1
  • 13
  • 33
  • Makes sense, thank you. Question: wouldn't the ```redirect()``` have to be before the ```connect()``` otherwise **/page/** would go to the controller? – sdexp Jan 09 '20 at 12:25
  • I always put the redirect it after the `connect()` and personally it has worked always perfectly like this for me. – Oris Sin Jan 09 '20 at 12:29
  • the rule doesn't match because /page/* != /page/, it requires /page/text to match. allowing you to catch /page/ and redirect to /page as required. it can be above or below – Steve Coverdale Jan 11 '20 at 08:30