Codeigniter - custom routes - codeigniter

Lets say I have a controller 'standard' with an action 'main'.
If I go to www.myapp.com/standard/main it will invoke the main action in the standard controller.
Now if I want to change the URL I go into the routes.php and set sth like the following:
$route['welcome'] = "standard/main";
Now I can visit www.myapp.com/welcome and it will invoke the same action.
However it is still possible to visit www.myapp.com/standard/main. I now have two routes which lead to the same controller action.
Is this the usual way or should I somehow disable the now unwanted www.myapp.com/standard/main route? If so, how would I do that?
Thanks in advance.

That is completely for you to decide the default behavior. If you decide to disable the original url, you can write something like
$route['standard/main'] = 'standard/404';
Or any custom location, it depends on your project and how you wish it should look like, for example you can 'block' any method from being accessed directly:
$route['standard/(:any)'] = 'standard/404';
But bear in mind, if you route like you did $route['welcome'] = "standard/main";, then you should always remember that the function $this->uri->segment(n) will show different values, for example if I will go to url yoursite.com/welcome/123, the value of $this->uri->segment(2) will be 123, but if I visit the original URL yoursite.com/standard/main/123, it's value will change to main.
Bear that in mind and decide for yourself!

Assuming that this is a common structure you'll be using, for each action, you can check the segment's in the URL and then redirect appropriately. In the case of going from standard/main to welcome, you would have the following:
class Standard extends CI_Controller {
public function main() {
if($this->uri->segment(1) == 'standard') {
redirect('welcome', 'location', '301');
}
}
}
This would then check the first segment in the URL and if it sees that you've come to this URL, redirect you to the appropriate route. This can then be applied to each action you want to do the same thing for. Supplying a 301 signifies a permanent redirect.
Update
Just found a similar (the same?) question: Only allow URL's specified in routes to be seen in Codeigniter

Related

How can I shorten routes in Codeigniter for certain requests?

I have a page that has this category URL website.com/category/view/honda-red-car and I just want it to say http://website.com/honda-red-car no html or php and get rid of the category view in the URL.. this website has been done using the CodeIgniter framework..
also this product view URL website.com/product/details/13/honda-accord-red-car
and I want it to be website.com/honda-accord-red-car PLEASE HELP!!!
I cannot find correct instructions on what I am doing wrong??
In Routes.php you need to create one like so
$route['mycar'] = "controller_name/function_name";
So for your example it would be:
$route['honda-red-car] = "category/view/honda-red-car";
Take a look into the URI Routing part of the user guide.
If you have concrete set of urls that you want to route then by adding rules to the application/config/routes.php you should be able to achieve what you want.
If you want some general solution (any uri segment can be a product/details page) then you might need to add every other url explicitly to the routes.php config file and set up a catch-all rule to route everything else to the right controller/method. Remember to handle 404 urls too!
Examples:
Lets say the /honda-red-car is something special and you want only this one to be redirected internally you write:
$routes['honda-red-car'] = 'product/details/13/honda-accord-red-car';
If you want to generalize everything that starts with the honda- string you do:
$routes['(honda-.*)'] = 'product/details_by_slug/$1'; // imaginary endpoint
These rules are used inside a preg_replace() call passing in the key as the pattern, and the value as the replace string, so the () are for capture groups, $1 for placing the capture part.
Be careful with the patterns, if they are too general they might catch every request coming in, so:
$routes['(.*)'] = 'product/details_by_slug/$1';
While it would certainly work for any car name like suzuki-swift-car too it would catch the ordinary root url, or the product/details/42 request too.
These rules are evaulated top to bottom, so start with specific rules at the top and leave general rules at the end of the file.

Change CodeIgniter route for static pages and auth login [duplicate]

I have a problem with Codeigniter routes. I would like to all registered users on my site gets its own "directory", for example: www.example.com/username1, www.example.com/username2. This "directory" should map to the controller "polica", method "ogled", parameter "username1".
If I do like this, then each controller is mapped to this route: "polica/ogled/parameter". It's not OK:
$route["(:any)"] = "polica/ogled/$1";
This works, but I have always manually entered info in routes.php:
$route["username1"] = "polica/ogled/username1";
How do I do so that this will be automated?
UPDATE:
For example, I have controller with name ads. For example, if you go to www.example.com/ads/
there will be listed ads. If you are go to www.example.com/username1 there are listed ads by user username1. There is also controller user, profile, latest,...
My Current routes.php:
$route['oglasi'] = 'oglasi';
$route['(:any)'] = "polica/ogled/$1"
$route['default_controller'] = 'domov';
$route['404_override'] = '';
I solved problem with this code:
$route['oglasi/(:any)'] = 'oglasi/$1';
$route['(:any)'] = "polica/ogled/$1"
$route['default_controller'] = 'domov';
$route['404_override'] = '';
Regards, Mario
The problem with your route is that by using :any you match, actually...ANY route, so you're pretty much stuck there.
I think you might have two solutions:
1)You can selectively re-route all your sites controller individually, like:
$route['aboutus'] = "aboutus";
$route['where-we-are'] = "whereweare";
//And do this for all your site's controllers
//Finally:
$route['(:any)'] = "polica/ogled/$1";
All these routes must come BEFORE the ANY, since they are read in the order they are presented, and if you place the :any at the beginning it will happily skip all the rest.
EDIT after comment:
What I mean is, if you're going to match against ANY segment, this means that you cannot use any controller at all (which is, by default, the first URI segment), since the router will always re-route you using your defined law.
In order to allow CI to execute other controllers (whatever they are, I just used some common web pages, but can be literally everything), you need to allow them by excluding them from the re-routing. And you can achieve this by placing them before your ANY rule, so that everytime CI passed through your routing rules it parses first the one you "escaped", and ONLY if they don't match anything it found on the URL, it passes on to the :ANY rule.
I know that this is a code verbosity nonetheless, but they'll surely be less than 6K as you said.
Since I don't know the actual structure of your URLs and of your web application, it's the only solution that comes to my mind. If you provide further information, such as how are shaped the regular urls of your app, then I can update my answer
/end edit
This is not much a pratical solution, because it will require a lot of code, but if you want a design like that it's the only way that comes to my mind.
Also, consider you can use regexes as the $route index, but I don't think it can work here, as your usernames are unlikely matchable in this fashion, but I just wanted to point out the possibility.
OR
2) You can change your design pattern slightly, and assign another route to usernames, something along the line of
$route['user/(:any)'] = "polica/ogled/$1";
This will generate quite pretty (and semantic) URLs nonetheless, and will avoid all the hassle of escaping the other routes.
view this:
http://www.web-and-development.com/codeigniter-minimize-url-and-remove-index-php/
which includes remove index.php/remove 1st url segment/remove 2st url sigment/routing automatically.it will very helpful for you.
I was struggling with this same problem very recently. I created something that worked for me this way:
Define a "redirect" controller with a remap method. This will allow you to gather the requests sent to the contoller with any proceeding variable string into one function. So if a request is made to http://yoursite/jeff/ or http://yoursite/jamie it won't hit those methods but instead hit http://yoursite/ remap function. (even if those methods/names don't exist and even if you have an index function, it supersedes it). In the _Remap method you could define a conditional switch which then works with the rest of your code re-directing the user any way you want.
You should then define this re-direct controller as the default one and set up your routes like so:
$route['(.*)'] = "redirect/index/$1";
$route['default_controller'] = "redirect";
This is at first a bit of a problem because this will basically force everything to be re-directed to this controller no matter what and ultimately through this _remap switch.
But what you could do is define the rules/routes that you don't want to abide to this condition above those route statements.
i.e
$route['myroute'] = "myroute";
$route['(.*)'] = "redirect/index/$1";
$route['default_controller'] = "redirect";
I found that this produces a nice system where I can have as many variable users as are defined where I'm able to redirect them easily based on what they stand for through one controller.
Another way would be declaring an array with your intenal controllers and redirect everything else to the user controller like this in your routes.php file from codeigniter:
$controllers=array('admin', 'user', 'blog', 'api');
if(array_search($this->uri->segment(1), $controllers)){
$route['.*'] = "polica/ogled/$1";
}

localized routes solution

I built a french/english app and I would like to use the same controller/view for both language but to have a different route that is map to the current language. Let say I have website.com/Account/Register that return to my Account controller and Register action, I would love to have a route that is website.com/Comptes/Inscription. I know that I can add a custom route in the RegisterRoute section like so :
routes.MapRoute(
"AccountFr", // Route name
"comptes/inscription", // URL with parameters
new { controller = "Account", action = "Register" } // Parameter defaults
);
But it will need a lot of [boring] code to write all the possibles routes and also, I think it won't work when I will use T4MVC as #Url.Action(MVC.Account.Register()) will return /Account/Register no mater if I'm in french or in english.
Anyone as suggestions/ideas for this problem?
Thanks!
EDIT
Since it does not seem to have a good solution using T4MVC does anyone have an other good solution?
Unfortunately, this won't easily work with T4MVC. The root of the problem is that when going through T4MVC, you can't pick a specific route. Instead, the route gets selected based on the Controller, action and parameters.

How can I prevent duplicate content when re-routing pages in CodeIgniter?

Say I have a controller, "Articles" but I want it to appear as a sub-folder (e.g. "blog/articles"), I can add a route like this:
$route['blog/articles'] = 'articles';
$route['blog/articles/(:any)'] = 'articles/$1';
This works fine, the only problem now is that example.com/articles and example.com/blog/articles both use the Articles controller and thus resolve to the same content. Is there a way to prevent this?
To add a little more clarity in case people aren't understanding:
In this example, I don't have a 'blog' controller, but I want 'articles' etc to appear to be in that subfolder (it's an organization thing).
I could have a blog controller with an 'articles' function, but I'm likely to have a bunch of 'subcontrollers' and want to separate the functionality (otherwise I could end up with 30+ functions for separate entities in the blog controller).
I want example.com/articles to return a 404 since that is not the correct URL, example.com/blog/articles is.
Shove this in your controller:
function __construct()
{
parent::Controller();
$this->uri->uri_segment(1) == 'blog' OR show_404();
}
You can use subfolders in Codeigniter controllers, so in CI, the following directory structure works:
application/controllers/blog/articles.php and is then accessed at
http://example.com/blog/articles/*.
If, for some reason, you're set on routing instead of accessing the controllers in folders (you want to have a blog controller, for example, and don't want to route to it), you can do as suggested above and add the test for 'blog' to the constructor.
If you're in PHP5, you can use the constructor function like this:
function __construct()
{
parent::Controller();
$this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
or, in PHP4, like this:
function Articles()
{
parent::Controller();
$this->uri->uri_segment(1) == 'blog' OR redirect('/blog/articles');
}
I would suggest using redirect('blog/articles') instead of show_404(), though, so that you're directing users who hit /articles to the correct location, instead of just showing them a 404 page.
Routing there does not mean it will use a different controller, it just creates alias url segment to same controller. The way will be to create another controller if you are looking to use a different controller for those url segments.
If both /blog/ and /articles/ use the same controller, you can reroute one of them to a different one by just adding a new rule in your routes file.

how to create Codeigniter route that doesn't override the other controller routes?

I've got a lot controller in my Codeigniter apps, ex: Signup, Profile, Main, etc..
Now I want to build "User" controller.
what I want:
if people goes to url: example.com/signup, I want use default route to "Signup" Controller
if people goes to url: example.com/bobby.ariffin, I want to reroute this to "User" Controller because the url not handled by any Controller in my apps.
I had create this in my config/routes.php:
$route['(:any)'] = "user";
but it's override all the route in my apps to "User" Controller.
Is there any simple route for Codeigniter that doesn't override the other controller routes?
Update---
I've got simple regex for this problem, from: Daniel Errante's Blog
$route['^(?!ezstore|ezsell|login).*'] = “home/$0″;
where ezstore, ezsell, and login are the name of controller in Your Apps.
You can also use a foreach statement for this. That way you can keep your controllers in a nice neat list.
$controller_list = array('auth','dashboard','login','50_other_controllers');
foreach($controller_list as $controller_name)
{
$route[$controller_item] = $controller_name;
}
$route['(:any)'] = "user/display/$1";
You're going to have to explicitly define all of those routes. Otherwise you will always end up at the "user_controller".
$route['signup'] = "signup";
$route['(:any)'] = "user/display/$1";
or something similar. They are ran in order, so what ever is defined first, is going to happen first. So if you catch (:any), you're going to send ANYTHING to that controller.
Also keep in mind that you can use regular expressions, so if you know there is always going to be a '.' in there, you could test for that.

Resources