CodeIgniter默认路由配置:域名后直接传递参数是否可行?
Great question! You can absolutely achieve the URL structure www.example.com/param in CodeIgniter, but it doesn’t work with the framework’s default routing out of the box—here’s exactly how to set it up:
1. Understand the Default Routing Limitation
By default, CodeIgniter follows the pattern controller/method/parameter. So a URL like www.example.com/home/show/param would map to the show method in the Home controller, passing param as an argument. The default setup doesn’t support parameters directly after the domain because it expects a controller (and optionally a method) first.
2. Create a Custom Route
To make www.example.com/param work, you’ll need to define a custom route in application/config/routes.php. Here’s how:
Basic Single Parameter Route
Add this line at the bottom of your routes file (order matters—this rule will catch any URL that doesn’t match earlier routes):
$route['(:any)'] = 'home/show_param/$1';
(:any)is a wildcard that matches any string (letters, numbers, symbols) after the domain.home/show_param/$1tells CodeIgniter to send that wildcard value to theshow_parammethod in theHomecontroller, passing it as the first argument.
Restrict to Specific Parameter Formats (Optional)
If you only want to match parameters with a specific format (e.g., alphanumeric characters), use a regex route instead for better security and to avoid conflicting with other routes:
$route['([a-zA-Z0-9_-]+)'] = 'home/show_param/$1';
This will only match parameters made of letters, numbers, underscores, and hyphens.
3. Update Your Controller
Now, create or modify the Home controller to accept the parameter:
class Home extends CI_Controller { // Default method for root domain (www.example.com) public function index() { echo "Welcome to the homepage!"; } // Method to handle the parameter public function show_param($param) { // Use the parameter in your logic (escape it for safety!) echo "You passed the parameter: " . htmlspecialchars($param); // Or load a view with the parameter data // $this->load->view('param_page', ['param' => $param]); } }
4. Critical Notes
- Route Order: Always put this wildcard route at the end of your
routes.phpfile. Any routes defined after it will be ignored because(:any)matches everything. For example, if you have a route forwww.example.com/about, define that before the wildcard:$route['about'] = 'home/about'; $route['(:any)'] = 'home/show_param/$1'; // Goes last! - Root Domain Access: Make sure your
$route['default_controller']is set to your main controller (e.g.,home) so visitingwww.example.comstill loads your homepage instead of triggering the parameter route.
That’s it! Now when users visit www.example.com/yourparam, it will route directly to your controller method with the parameter passed in.
内容的提问来源于stack exchange,提问作者A. K. M. Nazmul Hassan

