Handle trailing slash with Codeigniter 3

三世轮回 提交于 2021-01-29 03:44:51

问题


I have a database of articles with the urls as follow:

person/albert-einstein/ (trailing slash)

person/albert-einstein/1 (no trailing slash)

And I was wondering what was the best way to handle url trailing slashes in Codeigniter 3?

This is what I have done/test so far:

echo site_url('person/albert-einstein/'); # http://localhost/person/albert-einstein                              
echo base_url('person/albert-einstein/'); # http://localhost/person/albert-einstein                              
echo site_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1                 
echo base_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1

Then I edited config.php to set:

$config['url_suffix'] = '/';

and printed again the urls:

echo site_url('person/albert-einstein/'); # http://localhost/person/albert-einstein/                              
echo base_url('person/albert-einstein/'); # http://localhost/person/albert-einstein                              
echo site_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1/            
echo base_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1

Now I can select site_url() or base_url() to print the url with trailing slash or without it. But now on my views I have to be very careful to which one I use and I'd rather use a function that respects the url I pass and return it with trailing slash if it have or don't add one if it doesn't have it.

And yes, I can definitely extend the helper and write a function like: print_url() that does what I want but I wanted to see if there's something I'm missing here. Thank you.


回答1:


You can use apache rewite rule for forcing trailing slash:

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

For removing trailing slash you can use:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

I used this good base of .htaccess snippets.



来源:https://stackoverflow.com/questions/36524343/handle-trailing-slash-with-codeigniter-3

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