2

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?

yesman
  • 7,165
  • 15
  • 52
  • 117

3 Answers3

2

Anubhavs answer is technically correct but the assumption that this is not already implemented in the framework is wrong. In fact redirect-routes are part of the core:

See http://api.cakephp.org/2.4/class-Router.html#_redirect

Connects a new redirection Route in the router.

Redirection routes are different from normal routes as they perform an actual header redirection if a match is found. The redirection can occur within your application or redirect to an outside location.

Examples:

Router::redirect('/home/*', array('controller' => 'posts', 'action' => 'view'), array('persist' => true));

Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the redirect destination allows you to use other routes to define where a URL string should be redirected to.

Router::redirect('/posts/*', 'http://google.com', array('status' => 302));

Redirects /posts/* to http://google.com with a HTTP status of 302

floriank
  • 25,546
  • 9
  • 42
  • 66
0
  1. You could redirect /posts to the homepage, for example:

    Router::connect('/posts', array('controller' => 'pages', 'action' => 'display', 'home'));

  2. You could just rename the PostsController and call it NewsController, if you want to use this term.

cornelb
  • 6,046
  • 3
  • 19
  • 30
0

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.

Anubhav
  • 1,605
  • 4
  • 18
  • 31
  • Thanks, this works well. Lets just hope the CakePHP team will add this functionality at a later date. – yesman Jan 19 '14 at 16:02
  • That's not true, he re-invented the wheel, this is already a core feature, see http://api.cakephp.org/2.4/class-Router.html#_redirect – floriank Jan 19 '14 at 17:23