【问题标题】:Handle trailing slash with Codeigniter 3使用 Codeigniter 3 处理斜杠
【发布时间】:2016-07-31 04:15:57
【问题描述】:

我有一个文章数据库,其网址如下:

person/albert-einstein/(斜杠)

person/albert-einstein/1(无斜杠)

我想知道在 Codeigniter 3 中处理 url 尾部斜杠的最佳方法是什么?

这是我到目前为止所做/测试的:

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设置:

$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。但是现在根据我的观点,我必须非常小心我使用哪一个,我宁愿使用一个尊重我传递的 url 的函数,如果它有或不添加一个斜杠,则返回它有它。

是的,我绝对可以扩展帮助程序并编写如下函数:print_url() 可以满足我的要求,但我想看看这里是否缺少一些东西。谢谢你。

【问题讨论】:

    标签: php codeigniter trailing-slash


    【解决方案1】:

    您可以使用 apache 重写规则来强制使用斜杠:

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

    要删除尾部斜杠,您可以使用:

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

    我使用了 good base 中的 .htaccess sn-ps。

    【讨论】:

    • 感谢您对我的问题感兴趣,但请记住,对于我的不同部分,我使用urls 带有斜杠和不带斜杠地点。所以你使用mod_rewrite 的解决方案并不真正适用于我的朋友这个问题。 :-)
    • 我遵循了这个请求:“我宁愿使用一个尊重我传递的 url 的函数,如果它有或者不添加一个斜杠,如果它没有它,我会用斜杠返回它”。首先 sn-p 允许它。
    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2012-12-19
    相关资源
    最近更新 更多