Вопрос

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?

Это было полезно?

Решение 2

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.

Другие советы

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

  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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top