Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 Redirects in CakePHP 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>

like image 409
sdexp Avatar asked Apr 19 '26 06:04

sdexp


1 Answers

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.

like image 134
Oris Sin Avatar answered Apr 21 '26 22:04

Oris Sin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!