问题
If I have a controller called articles, which has a method called view_articles, a user can type in http://example.com/articles/view_articles/some-post and have it return a page.
I have specified a route to be http://example.com/article/post-name. How can I make it so that only the URL specified in the route is visible? Is there a way for articles/view_articles/some-post to show a 404 instead of showing the same page as the route URL?
I am trying to prevent duplication for SEO purposes.
回答1:
Use $this->uri->segment(n)
as part of the URI class inside of view_articles
to redirect traffic to your route if the URI contains view_articles
as it's second segment.
回答2:
You can always make default routing to a 404 page by correctly defining routes in your routes.php
file:
$routes['article/(:any)'] = 'articles/view_articles/$1';
$routes['(:any)'] = 'main/e404';
As stated by CodeIgniter user guide:
Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
So you can basically define all you want to be seen at the beginning of the file and block everything else on the last line.
As for your main(can be any other) controller's 404 method -
function e404() {
show_404();
}
回答3:
I'v done that in other tricky way, first of all you should add some code to __construct function in sys/core/Controller.php you can check whether the requested url is in routes or not by this code
if(!isset($this->router->routes[uri_string()])){
show_404(); // Or whatever you want ...
}
来源:https://stackoverflow.com/questions/12626700/only-allow-urls-specified-in-routes-to-be-seen-in-codeigniter