Pretty URL's with CodeIgniter

北城余情 提交于 2019-12-11 21:26:49

问题


I'm fairly new to CI and have been trying out how to produce clean URL's. I have accomplished this task before without using a framework by editing my .htaccess file as follows.

RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile.php?id=$1 [L]

With CI, I have tried the following:

#Get rid of the index.php that's in the URL by default
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Profile page
RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile?id=$1 [L]

I know that by default, the value after the name of the controller in the URL (in this case, the Profile controller), will invoke the function with the same name inside the controller class. But, if there is no value in the URL specified after the controller, by default, the index function will be invoked. I plan on leaving the function name blank so that the index function will be invoked by default. But, the rewrite rule isn't working.

Any ideas?


回答1:


With .htaccess you can do like this

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

# Profile page
RewriteCond %{REQUEST_URI} !^/(css|js|img)/
RewriteRule ^profile/([^/]*)$ profile/index/$1 [L]

In rewrite you have to mention the function name whether it is the index function or any other

Same as you can utilize the CI routing routes.php

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

Now in index function of profile you can get the parameter

function index($id) {
echo $id;
echo $this->uri->segment(3);
//Both will result the same 
}


来源:https://stackoverflow.com/questions/17584883/pretty-urls-with-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!