Codeigniter URL Rewriting
mostly we need to rewrite URLs to provide user friendly URLs of projects.
In CodeIgniter its much simple rather than manual writing HTAccess Rules.
Suppose you have :
- Controller (users)
- Function (index) list of all users
- Function (add) add user
- Function (view) view user
- Function (update) update user information
- Function (delete) delete user
Normally URLs will be :
- www.example.com/users/index/
- www.example.com/users/add/
- www.example.com/users/view/
- www.example.com/users/update/
- www.example.com/users/delete/
But you want that URLs should be:
- www.example.com/users/
- www.example.com/add-user/
- www.example.com/view-user/
- www.example.com/update-user/
- www.example.com/delete-user/
You do not need to add HTAccess rules in CodeIgnitor.
Just go to /application/config/routes.php
Aprx line 42
add following lines:
- $route[‘users’] = “users/index/”;
- $route[‘add-user’] = “users/add/”;
- $route[‘view-user’] = “users/view/”;
- $route[‘update-user’] = “users/update/”;
- $route[‘delete-user’] = “users/delete/”;
That’s All.
Now you can update your hyperlinks and rewrite rules will be done.
You open path www.example.com/add-user/
it will be opened www.example.com/users/add/
Enjoy 🙂
Thank You . You saved me from a lot of headache. I preapred myself to spend hours on fixing the htaccess to work on categories and other urls n never knew about routes so far.
so nice of you and wish you good luck.
can you let me know if i can route all image requests to a specific folder.
like should be routed to /assets/images/site/logo.png
Hi thanks for your comments.
to access images, you can create a function same as base_url() … you can create images_url() and set path in that.
Feel free to ask queries.
thanks
Thanks. you saved a lot of time. but i want to make dynamic route paths. like my footer links are dynamic and added/deleted from admin side.Admin created pages and title of these pages will be viewed in footer, admin adds slug for any page (e.g page[‘title’]=’About Us’, page[‘slug’]=’about_us’). Now this slug name will be sent to the controller.How to make url for this type of scenario.
Hi Mobeen, Can you please tell me exact scenario that you have page slug as parameter to a controller’s function something like this domain.com/controller/function/about_us
or you have a controller for about_us something like this
domain.com/about_us
then I can tell you a better answer.
thanks
Hi,
Great information.
I want to change below URL in Codeignitor:
Current URL: http://example.com/ad/detail/78/make/1/model/4
Required URL: http://example.com/ad/want-to-sale-something-78
I would really appreciate, if anybody guide me how to rewrite URL in the Codeignitor.
Thanks,
Muhammad Kamran
For that I am sure it will be something
$route[‘ad/want-to-sale-something-(.*)’] = “ad/detail/$1/make/1/model/4”;
Further, You can view this link as reference
http://stackoverflow.com/questions/10780416/codeigniter-routing-url-with-product-name-to-product-id
Feel free to contact me back if need more assistance.
Thanks
Thanks, Great information.
I want to change Url
Original Url http://example.com/category/index/2
Change To http://example.com/cat/productname-productid.html
Please guide how to make this dynamic url.
Thanks
Hi Sandeep Barala,
I am sure this will work.
$route[‘(.*)/(.*)-(.*)’] = “products/detail/$3″;
Here :
first : (.*) -> shows category name
second :(.*) -> product name
third : (.*) -> product id
we will parse third parameter and based on that we can get information of product and then also get category information.
Feel free to contact if issue not resolved.
Thanks
Thanks Naveed Ramzan. Yes It is working.
Current URL : http://example.com/shop/advancesearchresult?keywords=12&x=-683&y=-334&catidtobeparent=All+Categories&inc_subcat=1&manufacturers_id=&pfrom=&pto=&dfrom=&dto=
want to change
http://example.com/shop/result.html?keywords=12&x=-683&y=-334&catidtobeparent=All+Categories&inc_subcat=1&manufacturers_id=&pfrom=&pto=&dfrom=&dto=
You Welcome 🙂
You can do like:
$route[‘shop/result.html?keywords=(.*)&x=(.*)&y=(.*)&catidtobeparent=(.*)&inc_subcat=(.*)&manufacturers_id=(.*)&pfrom=(.*)&pto=(.*)&dto=(.*)’] = “shop/advancesearchresult?keywords=$1&x=$2&y=$3&catidtobeparent=$4&inc_subcat=$5&manufacturers_id=$6&pfrom=$7&pto=$8&dto=$9″;
And so on.
Thanks
Awesome! You are Genius.. Thanks For Support
Thanks 🙂
Hello Naveed,
My URL is http://example.com and when I hit this url then it should be redirect http://example.com/en . please tell what can i do ?
Thanks
Sandeep
My site is theme based and In My_loader.php theme fucntion is not calling . can you suggest me why ?
Hi Sandeep,
sorry for late actually I was not available to reply.
for redirecting http://www.example.com to http://www.example.com/en
you can set in routes.php for default controller
$route[‘default_controller’] = ‘en’; // or you can set controller and then function
As far as My_loader.php I would like to see the code or application first then I can suggest.
Thanks
My Url IS : http://atlasengg.aseuminfotech.com/index.php/index
I Want To : http://atlasengg.aseuminfotech.com/index
Remove index.php in codeigniter, Plz Help Me.
RewriteRule ^(.*)$ index.php/$1 [L]
Make sure that .htaccess contains this line.
Thanks
HI Naveed,
Actually, i am facing one issue i.e
I have url like this http://mydomain.com/blog/category/10/category-name
I want like this http://mydomain.com/blog/category/category-name
It should work without any change in the coding and my code should read id becuase it display record based on id not by category name.
Can you help me in this.
I have tried in the routes.php but nothing happend.
Can i hide one parameter like this:-
$route[“category/$2”] = “category/$1/$2”;
Thanks a lot !
Dear Naveed Ramzan,
I’m fetching a problem in codeigniter recently.
I tried it in many ways. used _remap function and route.php as well as some other
technique but failed. If you have solved this problem please give me the code. It’ll
help me a lot and save my time.
I need to rewrite my url in codeigniter dynamically.
Say my url
mysitename.com/controller/method/id1.
mysitename.com/controller/method/id2
mysitename.com/controller/method/id3
………
mysitename.com/controller/method/idN
I want to remove method name from url and id would be my variable. Just as follows
mysitename.com/controller/search-engine-friendly-string1
mysitename.com/controller/search-engine-friendly-string2
mysitename.com/controller/search-engine-friendly-string3
…..
mysitename.com/controller/search-engine-friendly-stringN
You are expert in CodeIgniger. I am sure u have the solution.
Hope I explained the problem. Thanks in advance…
Dear Salsauzzaman Khan,
you need to write a route line in routes.php
$route[“controller/user-friendly-url-$1”] = “controller/method/$1″;
I am sure it will be helpful
Thanks
it’s not working when i am trying this
$route[‘default_controller’] = “welcome”;
$route[“contactus”] = ‘contactus’;
$route[“content-(.*)”] = ‘content/$1’;
$route[‘404_override’] = ”;
Dear NoorKhan,
for default_controller, welcome should be a controller name.
Same for contactus, it should be controller name
the method of calling routes is like
$route[“content-(.*)”] = ‘controller/method/$1’; //$1 is parameter
Please let me know if you need further assistance.
Thanks
Dear Naveed
Thanks for Prompt reply
welcome is my controller name
class Welcome extends CI_Controller
contactus is also my controller name
Ok that’s good.
Then any error or any other page occurring.
Can you send me the demo site link ?
I am working on localhost
$route[“content-(.*)”] = “content/page/$1″;
class content extends CI_Controller {
public function index()
{
//$this->load->model(‘content_model’);
//$this->load->view(‘content’);
}
function page($url_title = ”)
{
$id = $_REQUEST;
print_r($id);
$this->load->model(‘content_model’);
$this->load->view(‘content’);
}
}
Can you please replace
print_r($id);
to
print_r($url_title);
and tell me the result ?
Thanks Above issues has been resolved it was my mistake 🙂
$route[“contactus”] = ‘contactus’;
$route[“content-(.*)”] = “content/page/$1”;
$route[“(.*)-(.*)”] = “brandsdetail/brandprofile/$1”;
$route[“stores”] = “stores”;
$route[‘(.*)/(.*)’] = “storedetail/profile/$1”;
All are working fine when i put last line on route file and then try to execute it’s go to brandsdetail (means it’s execute line 3)
OK fine.
as far as brandsdetail and store detail.
it should be recognized with dash (-) and slash (/) and then redirect to relevant route.
Is not working like that ?
No it’s not working it’s goes to branddetail page
Ok what if you attach word in url.
Such as :
$route[“brand-(.*)-(.*)”] = “brandsdetail/brandprofile/$1″;
$route[“store/(.*)/(.*)”] = “storedetail/profile/$1″;
brand and store are more seo friendly words.
let me test then i will inform you
Thanks
It’s working fine now 😀
Thanks
Ok good.
Welcome
_remap() is also a powerful function in CI for SEO friendly url. please share some article about it as well.
HI Naveed,
Actually, i am facing one issue i.e
I have url like this http://mydomain.com/property_details/$id/$url_title
I want like this http://mydomain.com/property_detail/$slug
It should work without any change in the coding and my code should read id becuase it display record based on id not by category name.
Can you help me in this.
Thanks a lot !
Hi Nimmy,
If you try like this.
$route[‘property_detail/(.*)-(.*)’] = “controller/property_detail/$1/$2″;
Here $1 will be id
and $2 will be slug
both will be tackled in url.
Id you can pass to controller’s method
slug will be helpful for SEO Friendly URLs.
Please let me know if you need more assistance.
Thanks
Great information but sir I have some problem it’s not working with me please if you help me to change the url http://localhost/dgmm/procedures/index/10011
to http://localhost/dgmm/
thanks if you help me
Hi Tariq,
If its your default page or home page of website then you can set in as default path.
$route[“default”] = “procedures/index/10011”;
hi Naveed ,
First of all thanks for a great information..
my problem is
i have a url like http://www.example.com/controller/mobile/4(4 is mobile id)
i want this http://www.example.com/mobile/nokia
$route[‘mobile/nokia’] = “controller/mobile/4″;
But in this way, nokia will be a slug/keyword while passing in parameter its ID only.
so best is to pass name instead of id like this
$route[‘mobile/(.*)’] = “controller/mobile/$1″; // here set variable in where clause
or you can do like this
$route[‘mobile/4-nokia’] = “controller/mobile/$1/$2″; // in this way, you can map $1 as ID and second paramter as empty
A.A brother i want to change this URL to
http://www.mobile57.com/pms_v2/product/phones/1
AND
http://www.mobile57.com/pms_v2/product/view/phones/samsung/2
To
http://www.mobile57.com/pms_v2/product/phones/samsung/2
AND
http://www.mobile57.com/pms_v2/product/detail/phones/samsung/58
to
http://www.mobile57.com/pms_v2/product/phones/samsung/58
can you please ANS me my problem I m very thanks full to you..zahid hussain
A.A brother i want to change this URL to
current url
http://www.mobile57.com/pms_v2/product/index/phones/1
To
http://www.mobile57.com/pms_v2/product/phones/1
AND
http://www.mobile57.com/pms_v2/product/view/phones/samsung/2
To
http://www.mobile57.com/pms_v2/product/phones/samsung/2
AND
http://www.mobile57.com/pms_v2/product/detail/phones/samsung/58
to
http://www.mobile57.com/pms_v2/product/phones/samsung/58
can you please ANS me my problem I m very thanks full to you..zahid hussain
This was working
$route[‘(:any)’]= “product/index/$1”;
$route[‘(:any)’]= “product/view/$1”;
but when execute last route execute only one execute why ?
just one function execute
how i chnage in $route[‘(:any)’] for specific function
Well for the last comment
$route[‘(:any)’]= “product/index/$1″;
$route[‘(:any)’]= “product/view/$1″;
but when execute last route execute only one execute why ?
Its in fact overwriting.
you need to give a token or path instead of only :any.
such as
$route[‘list-(:any)’]= “product/index/$1″;
$route[‘detail-(:any)’]= “product/view/$1″;
for above two comments, I am sure you can fix as my given example.
or you can send me your effort and i can update you.
Thanks for reply but i can not understand token
my orignal path is
http://localhost/pms/product/index/phones/1
but i want
http://localhost/pms/product/phones/1
how your solotion not working i can not understand after your solotion waht was link can you mention please ?
$route[‘list-(:any)’]= “product/index/$1″;
what was list and where i use it waht is new link after this because when i add it
error page was not found
thanks for your update
this is my rout file
/* use for admin */
$route[‘addproductmeta’] = “cms/addproductmeta”;
$route[‘productinfo/(:num)’] = “cms/productinfo/$1”;
/* use for web */
$route[‘default_controller’] = “webmain”;
/* i change it but it not work */
/*$route[‘list-(:any)’]= “product/index/$1”;
$route[‘list2-(:any)’]= “product/view/$1″*/;
$route[‘404_override’] = ”;
Is it possible to set dynamic country code before controller?
like
http://www.funonsite.com/product/index url convert to usa country
http://www.funonsite.com/us/product/index
please help proper guide and code
i m very trouble
well you can map like this.
$route[‘us/product/index’] = “product/index”;
yes brother
hi
sir i want to remove index.php from this path
http://localhost/travel/index.php/holiday-package
without using .htaccess file. it is possible ?
$route[‘holiday-package’] = “controller/function/”;
update this in app/Config/routes.php
Hi,
I have a situation where my slideshow displays fine on localhost/citylights/ but when i go to the url: localhost/citylights/en/1/some-page everything displays okay except the slideshow images.
my .htaccess is:
# Development
RewriteEngine On
RewriteBase /citylights/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index.php|images|scripts|styles|vendor|robots.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
My routes.php is:
$route[‘default_controller’] = “content”;
$route[‘en/(:num)/(:any)’] = “content/en/$1”;
The issue i think is two-fold:
1. My images display fine when in localhost/citylights/ but not when in the url sub-directory path of localhost/citylights/en/1/ even though i am using base_url() (where base_url is set as localhost/citylights/)
2. My javascript (that does slideshow) is set with a path of “assets/js/some-js.js” but when i try to set path using base_url() nothing works on anything.
Therefore path is all correct when in localhost/citylights/ but moment i go to localhost/citylights/en/1/some-page all the paths for the images and js mess up. Any ideas??
thx
(sorry – base_url() is set as ” as this is being done in the .htaccess)
Hello Naveed,
Great tips on rewriting using Codeigniter.
I have a different kind of query regarding rewriting URL
This is the current URL
http://localhost/mywebsite/page/
And I want it to work as root url as
http://localhost/mywebsite
Which I have already done by adding it as default controller in config.php
But now I have another URL as
http://localhost/mywebsite/page/mypagename
Which should open as
http://localhost/mywebsite/mypagename
How can I do it?
Thanks in advance,
Aslam
$route[‘mypagename’] = “page/mypagename″;
You need to set a route in your routes.php.
I have URL http://localhost/CI/index.php/news/first/1 and want to convert this into http://localhost/CI/index.php/news/1
Please guide me through this URL Rewriting.
Thanks
Hi Afzaal,
Can you please tell me what is First/ is it a function or why you are using this …
AoA
i am facing some issue
i have same function name for both userside and adminside but different controller name .so when i am routing so it all redirect to userside
Thanks in advance
nice solution for url rewrite in codeigniter.Good Job
In codeigniter is it possible to create url like below one
Original URL : http://www.xyz.com/foo
i want to convert original url to http://www.xyz.com/foo.php
with the help of htaccess or any other solution
Yes for that, I think you need to add rule in .htaccess that all pages should be accepted with .php.
Hi Naveed,
How to do if i want this:
Localhost/ci/index.php/main/wall/username
to (atleast):
Localhost/ci/wall/username
Or (better):
localhost/ci/username
Note: username is the parameter where shoud exist in the database. If not exist, the url entered (with or without string username) will directed to “page not found”. Not php error (if username is blank such as localhost/ci/(blank) or localhost/ci/wall/(blank). or mysql error (if the username doesnt exist in the database)
Yes you can do like localhost/ci/wall-username
and map this in routes.php
$route[‘wall-(.*)’] = “users/wall/$1”;
and in function
public function wall($username){}
and like this
MY
Assalamu Alaikum,
My Original URLs are
http://www.example.com/product/view/epson-tm-c3510-color-label-printer,
http://www.example.com/product/view/evolute-leopard-tablet-pos
My Target URL is this like
http://www.example.com/product/epson-tm-c3510-color-label-printer
and “epson-tm-c3510-color-label-printer” and “evolute-leopard-tablet-pos” are dynamic passing parameters .
So how can I change? Kindly help me
Well, you can save slug same as wordpress save for pages/posts.
Like if you save a product
Epson TM c3510 Color Label Printer so you can save slug epson-tm-c3510-color-label-printer and this slug should be unique.
and you can pass paramter in URL and get that in controller’s function (as you can see in original post)
I am sure it will be working otherwise please do email me.
Thanks
expect create url Like “mobiles?brand=[brand]”
and wanted to direct the user to brands_mobile/mobile_by_brand
what would be the route??
kindly guide me..
My url is : http://example.com/controller/method/id
I want url as : http://example.com/controller/method/product-name
I gave created a whole site with this logic so that i have to do something using htaccess.
I cant change whole site logic.
So please help me to solve this problem.
Well, you can pass parameter like
url.com/controller/method/product+name (using url_encode)
you are passing 1 parameter in function. its name is ID but you can change to NAME.
in function, you need to search products by name instead of product id. (use url_decode)
OR
if you want to make url like
url.com/controller/method/id-product+name
then do let me know.
my route file has route[‘(:any)’] = “web/index/$1” to bring URL friendly: localhost/my-slug-url, it works good (am using slugs from database), but my dashboard class does not work if I use the route[‘(:any)’] the problem is that how can I access the dashboard class “dashboard” (has functions add/remove/edit)
I want to make url : localhost/this-is-my-domain without using route ? the simple I can let you feel my issue is about … and even I can access other class and controller.
Hey Thanks man
it’s working for me
My category and sub category pages both run under same link
http://www.abc.net/category/index/7
No need to change to
http://www.abc.net/category/category name
Please help how?
$route[‘category/(.*)’] = “category/search/$1″;
Here I assume that function “search” is a function in category controller and parameter which we are passing is the category name
http://www.abc.net/category/mobile-phones
It will go to Category(Controller), search(function), mobile-phones (parameter)
hi kindly help me how to solve this
initial url
static page
http://www.example.com/page/about-us
i want this to be
http://www.example.com/about-us
category url
http://www.example.com/category/11/categoryname
i want this to be
http://www.example.com/categoryname
product url
http://www.example.com/products/12/productname
i want this to be
http://www.example.com/productname
$route[‘category/(.*)’] = “category/record/$1″; //here i assume record as function and parameter $1 is the name of category
as for as about us page
$route[‘about-us’] = “page/aboutUs″; // here i assume page as controller and aboutUs as function.
Here my url
http://demo.com/institute/details/106-aditi-mahavidyalaya-amv-delhi
I want url like this
http://reviewadda.com/institute/details/aditi-mahavidyalaya-amv-delhi
Plz help sir
In that case you need to set name as unique key or make slug as unique.
when saving name of institute save also slug. and parse that in URLs.
$route[‘institute/details/(.*)’] = ‘institutes/details/$1’; // here I am assuming institute as controller and detail as method.
how to hide id
problem url
http://www.example.com/controller/method/id-name-city
target url
http://www.example.com/controller/method/name-city
I also suggest you to make slug and pass that slug in URLs as key / id.
My Current URL:http://www.example.com/index.php/example/articles/NA__
Want to change as
http://www.example.com/index.php/example/articles/categoryname
Note:NA__ is category id
My Current URL:http://dealking.in/Snapdeal/41Samsung-16GB-MicroSDHC-EVO-Class-10-DK-bJSp6ST
Want to change as remove the 41 here 41 is a product id
http://dealking.in/Snapdeal/Samsung-16GB-MicroSDHC-EVO-Class-10-DK-bJSp6ST
Well, you can set title of product as unique slug :
$route[‘Snapdeal/(.*)’] = “controller/function/$1″; // here $1 is slug or title of product. and in db you can search product with its slug.
http://localhost:8080/real_estate/index.php/property/30/en/dubai-marina
i want to convert this to some thing like this
http://localhost:8080/real_estate/en/dubai-marina-30.html
You need to add plug-in of multi-lingual and it will update the url and their language.
http://stackoverflow.com/questions/13524174/how-to-make-multilingual-website-using-library-in-codeigniter
Maybe this will be more helpful.
language is already working i just want to customize the above url .according to you the above url is good for seo ? this one
http://localhost:8080/real_estate/index.php/property/30/en/dubai-marina
$route[‘(.*)-(d+)’] = “controller/function/$2″; here $2 is ID of record
Hello sir i have two controller having name holiday_detail and tour_packages into one floder name frontend and controller routes is
$route[‘default_controller’] = “home”;
$route[‘(:any)’] = “holiday/holiday_detail/$1”;
$route[‘(:any)’] = ‘package/tour_packages/$1’;
whats problem in this route??? because only tour_packages controller method working fine but holiday_detail controller method not show the page??? please help me…
In fact, you are mapping one url into two paths. You need to set separate url for these two.
Like
$route[‘default_controller’] = “home”;
$route[‘holiday/(:any)’] = “holiday/holiday_detail/$1”;
$route[‘package/(:any)’] = ‘package/tour_packages/$1’;
Now both separate urls will be mapped into two separate path.s
http://localhost:8012/dec_viraj/animal_28_12/Blogdetails/?ID=49
change this to
http://localhost:8012/dec_viraj/animal_28_12/49
$route[‘animal_28_12/(.*)’] = “animal_28_12/Blogdetails/$1”;
Here I assume that dynamic variable is only Blog ID.
404 page is coming
after using
$route[‘animal_28_12/(.*)’] = “animal_28_12/Blogdetails/$1”
in application\config\routes
blogdetails is my controller
OK and what is animal_28_12.
Please elaborate or do email at naveed.ramzan@gmail.com with more detail so I can guide you to solve this.
Thanks
it will the folder in which i have kept my codignighter files i.e the root folder
$route[‘blog-(.*)’] = “Blogdetails/$1”;
now you need to tell in ID parameter that its blog id. just to identify in routes
I really like this post. I have started my new website if you really want to get updates about mobile phones just visit the following website. thanks a lot.
hello Naveed Ramzan
my current url:
http://jobber.akhbaar.pk/Site/jobpaper/1/2017-05-07
in this url 1 is newspaper id that will change to other newspaper i want to change my url as
http://jobber.akhbaar.pk/Site/jobpaper/express-jobs/2017-05-07
well, you can use slug like name of news paper is “Express Jobs” and you can make its slug “express-jobs” and in URL you can pass that slug.
In Controller’s function, you can pass that slug as parameter and update where clause with slug.
I am sure it will work
can i send the link you check ?
http://www.domain.com/projects/explore/JZsia/project-name
We want to redirect it to
http://www.domain.com/1bhk-2bhk-3bhk-apartments-in-wagholi-pune
I am sure the project-name will be “1bhk-2bhk-3bhk-apartments-in-wagholi-pune”
So if yes, then you need to save permalinks and get record based on that.
Hi Naveed
Really appreciated your work. I have done URL Rewriting as you told above. It’s working fine for desktop and laptop but it doesn’t work for mobile view.
Like:
$route[“theory”] = “frontend/theory”;
Link: http://musiculus.com/theory
This is working fine on laptop and desktop but on mobile view this will not work and shown like:
Link: http://musiculus.com/frontend/theory
Thanks for any help.
I need a url is ‘xyz.com/category/tshirts/128’
but i need like this – ‘tshirts/128’
but ‘tshirts/128’ is dynamic ‘/category-names/category_id’
i tried this – https://stackoverflow.com/questions/35186185/hide-codeigniter-both-controller-and-method-name-from-url
but not working for me
You may try like
$route[‘(.*)/(.*)’] = “category/$1/$2”;
So here I assume that category is the controller and then we have 2 parameters.
Hii Sir,
My url: abc.com/categorytname/12/abc-xyz-pqr
In url contains categoryname,id,and product name but manually id change in url than data get these id but categoryname and product name as its in url.
After Id change url: abc.com/categorytname/13/abc-xyz-pqr
Well if you manually change ID in URL then definitely product name or category name will not be updated. Yes that can be done in constructor of base controller that if id and name is different then get record based on ID and redirect to updated URL.
But , My url based on routing.how to change constructor of base controller.
plz tell me. for exmple
great sharing thanks sir
Hello! Thank you very much for this instruction, which really helped me. Can I somehow pass utf8 in url? I want to write Georgian text, but get 404. Same text on English works well.