Welcome Guest, Not a member yet? Register   Sign In
URL Rewrite
#1

[eluser]Unknown[/eluser]
hi, i'm new to CodeIgniter and I want to ask about URL rewrite in CI.

I've managed to omit the inclusion of index.php so my URL is mysite/controller_name/method name.

for example : mysite.com/home/index

of course i've done the autoload controller in routes.ph so the url above is the same as

mysite.com

recently, i want to create a new page which will pass some variables. here's the url i intend to get to work.

mysite.com/read/novel-title/chapter-number as in
mysite.com/read/harry-potter/1

my question is, how should i do it? when i put the read function in home.php controller, i have to access mysite.com/home/read/harry-potter/1 to open the page which is quite tedious. i don't need the home part. on the other hand, if i create a new controller, read.php, i have to access mysite.com/read/index/harry-potter/1 or mysite.com/read/other-function-name/harry-potter/1 which is also tedious and ugly.

i hope my point is clear. thanks in advance.
#2

[eluser]mattpointblank[/eluser]
This is what routes.php inside your application/config/ folder. You can define regular expressions to forward your URLs like this:

Code:
$route['read/(:any)/(\d+)'] = "home/read/$2";

This code is pretty simple - the first part after the $route defines the URL you'd like users to see. The (:any) keyword simply means any combination of characters, eg. your novel title. The (\d+) means digit, so that's your chapter number.

In the other half of the statement is the method/controller you're using. The $2 refers to the second variable, eg the (\d+) or chapter number. In this example I've assumed your read() method only requires the chapter number, but if you need to pass it the name as well, just change it to "home/read/$1/$2". Make sense?

Bear in mind that when you start changing your routes, you may have to start manually adding everything. For example, if you wanted to remove /read/ from the URL altogether, you could do so using this method, but that would mean that every new controller/method you added would need to be manually added to routes.php as well, otherwise the wildcards will override it.




Theme © iAndrew 2016 - Forum software by © MyBB