CodeIgniter3路由配置求助:URL路由转换与URI段异常问题
Hey there, let's work through your two CodeIgniter 3 problems one by one:
1. Configuring Routing for http://domain.loc/controller/method/pram1/pram2
First, let's break down how CodeIgniter's default routing works. Out of the box, URLs in the format domain/controller/method/param1/param2 will automatically map to your controller's method with the specified parameters—you don't even need extra routing rules for this to work, as long as your controller and method exist.
If you're trying to create a custom alias (like shortening the URL or mapping a different path to this controller/method), here's how to set it up in application/config/routes.php:
// Example: Map a custom path to your target controller/method $route['custom-path/(:any)/(:any)'] = 'controller/method/$1/$2';
This rule lets users access http://domain.loc/custom-path/pram1/pram2 and have it routed directly to controller/method/pram1/pram2.
Your existing rule $route['class/method2/(:any)/(:any)'] = 'class/method2/$1/$2'; is actually redundant for default routing behavior, but it's harmless to keep if you want to explicitly define it.
2. Fixing URI Segment Parsing for http://domain.loc/controller/method/catagory/offset 10
The odd URI segment result you're seeing (array (size=1) 'P' => string '10') is almost definitely caused by the unencoded space in your URL. URLs don't support raw spaces—browsers usually convert them to %20, but manual spaces can trigger unexpected server-side parsing errors.
Here's how to resolve this:
Fix the URL structure: Replace the space with a slash to split the parameter into valid URI segments. Use
http://domain.loc/controller/method/catagory/offset/10instead. This way, CodeIgniter will parse the segments correctly as:- Segment 1:
controller - Segment 2:
method - Segment 3:
catagory - Segment 4:
offset - Segment 5:
10
- Segment 1:
If you must use spaces (not recommended): If you absolutely need to include a space, encode it as
%20or+(e.g.,http://domain.loc/controller/method/catagory/offset%2010). You'll also need to updateapplication/config/config.phpto allow spaces in URI characters:$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; // Added a space inside the allowed charsNote: Using spaces in URLs is generally bad practice—they can cause issues with caching, link sharing, and server parsing, so sticking to slashes or query parameters is a better approach.
Check for conflicting routes: Double-check
routes.phpfor any other rules that might be overriding or misparsing this URL. For example, a wildcard rule that's capturing unexpected parts of the URI.
内容的提问来源于stack exchange,提问作者imran

