phpcakephpcakephp-routing

Prevent CakePHP controller access with routing


I'm following the CakePHP blog tutorial, and at the moment the URL

/posts/view/1

Works. Using routing, I managed to create an alias news:

Router::connect('/news/:action/*', array('controller' => 'posts'));
Router::connect('/news/*', array('controller' => 'posts'));

This way, the URL

/news/view/1

Works as well. However, the /posts/ URL still work as well. How do I prevent URL's with /posts/ still working?


Solution

  • The answer of your question is little tricky, nothing has been there in cakephp documentation

    What I have done in the similar situation was given below:

    Step 1: I have define one routing rule in routes.php as

     Router::connect('/posts/*', 
                                array('controller' => 'posts', 
                                      'action' => 'handleRedirection')
                    );
    

    Step 2: I have created one function handleRedirection in posts controller

     function handleRedirection(){
      $url = str_replace('posts','news',$this->request->url)
      $this->redirect($url,'301');
     }
    

    See in the above example I am using 301 permanent redirection, so you can do something like this.