How to remove controller name from the URL in code

2019-01-27 00:21发布

问题:

I have controller named “profile” and the URL for user profile is www.example.com/profile/user

I am already using the rerouting of codeigniter in the routes file

$route['profile/(:any)'] = "profile/index"; 

what I am looking is to remove the profile controller name from the URL so it will be SEO and user friendly.

e.g

www.example.com/user

any suggestions?

回答1:

You may try any one of these

// url could be yourdomain/imran
$route['(:any)'] = 'profile/index/$1';
// url could be yourdomain/10
$route['(:num)'] = 'profile/index/$1';
// url could be yourdomain/imran10
$route['([a-zA-Z0-9]+)'] = "profile/index/$1";

Your class may look like this

class Profile extends CI_Controller {

    public function index($id)
    {
        // $id is your param
    }
}

Update : (Be careful)

Remember that, if you have a class Someclass and you use url like yourdomain/Someclass then this will be routed to profile/index/$1 if you have $route['(:any)'] or $route['([a-zA-Z0-9]+)'].



回答2:

You can use this in a route file:

$route['(:any)'] = "controller_name/$1";
$route['(:any)/(:any)'] = "controller_name/$1/$1";
$route['(:any)/(:any)/(:any)'] = "controller_name/$1/$1/$1";


回答3:

Try this:

$route['user'] = 'profile/user';

Dont know any generic way to do it

Possible duplicate of How to hide controller name in the url in CodeIgniter?



回答4:

If I understand your question correctly, you just want to add a catchall to the very end of your routes file. Like:

$route['(:any)'] = 'profile/index';

This will catch everything that isn't caught by another route, so make sure this script contains logic to determine when a 404 should be presented.