阻止直接从codeigniter子目录中的url访问控制器

时间:2016-02-09 09:22:25

标签: codeigniter codeigniter-2

这是我的控制器结构:

controllers
  |
  |__ posts
     |
     |__post.php

我已经通过更改routes.php文件

从网址中删除了目录名称
$route['post/posts_controller'] = 'posts/post/posts_controller';

但现在我想如果有人点击目录名称为http://localhost/url_routing/posts/post/posts_controller的完整网址 然后应该出现未找到的页面。

1 个答案:

答案 0 :(得分:2)

这是CodeIgniter的一个真正问题,可能会导致搜索引擎出现大量重复内容。我找到的唯一解决方法是覆盖路由器以仅使用routes.php而不使用文件夹/控制器名称。

  

应用/核心/ MY_Router.php

class MY_Router extends CI_Router {

    /**
     * Parse Routes
     *
     * Matches any routes that may exist in the config/routes.php file
     * against the URI to determine if the class/method need to be remapped.
     *
     * @return  void
     */
    protected function _parse_routes()
    {
        // Turn the segment array into a URI string
        $uri = implode('/', $this->uri->segments);

        // Get HTTP verb
        $http_verb = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : 'cli';

        // Loop through the route array looking for wildcards
        foreach ($this->routes as $key => $val)
        {
            // Check if route format is using HTTP verbs
            if (is_array($val))
            {
                $val = array_change_key_case($val, CASE_LOWER);
                if (isset($val[$http_verb]))
                {
                    $val = $val[$http_verb];
                }
                else
                {
                    continue;
                }
            }

            // Convert wildcards to RegEx
            $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);
            // Does the RegEx match?

            if (preg_match('#^'.$key.'$#', $uri, $matches))
            {
                // Are we using callbacks to process back-references?
                if ( ! is_string($val) && is_callable($val))
                {
                    // Remove the original string from the matches array.
                    array_shift($matches);

                    // Execute the callback using the values in matches as its parameters.
                    $val = call_user_func_array($val, $matches);
                }
                // Are we using the default routing method for back-references?
                elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE)
                {
                    $val = preg_replace('#^'.$key.'$#', $val, $uri);
                }

                $this->_set_request(explode('/', $val));
                return;
            }
        }

        return;
    }
}

这将导致CodeIgniter仅使用您的routes.php,所以我仍然想要使用CI路由,然后不要使用它。