使用Codeigniter 3处理尾随斜杠 [英] Handle trailing slash with Codeigniter 3
问题描述
我有一个包含以下网址的文章数据库:
I have a database of articles with the urls as follow:
person/albert-einstein/
(斜线)
person/albert-einstein/1
(不带斜杠)
我想知道在Codeigniter 3中处理URL尾部斜杠的最佳方法是什么?
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
然后我编辑了 config.php
进行设置:
Then I edited config.php
to set:
$config['url_suffix'] = '/';
并再次打印网址:
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
现在,我可以选择 site_url()
或 base_url()
来打印带有斜杠或不带斜杠的url.但是现在我的观点是,我必须非常小心使用哪一个,而我宁愿使用一个尊重我传递的网址的函数,如果有则返回带有斜杠的网址,如果没有则不加一个有它.
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.
是的,我可以肯定地扩展帮助程序,并编写一个函数: print_url()
,该函数可以实现我想要的功能,但是我想查看是否在此处缺少某些内容.谢谢你.
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.
推荐答案
您可以使用apache rewite规则强制使用斜杠:
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]
我使用了 .htaccess
片段的良好基础.
这篇关于使用Codeigniter 3处理尾随斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!