[英]Code Igniter - relative URLs stop working when URL ends in slash?
我正在尝试学习CI,并且刚刚通过了入门教程 。 我发现,如果我的URL以斜杠结尾,则某些链接HREF无效-例如,这些链接:
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>
<?php endforeach ?>
我上线时,故事的链接正常工作
/index.php/news
但是如果我在
/index.php/news/
就像我说的那样,这对本教程来说是正确的,所以我不确定最新情况。
我可以使HREF成为绝对...。
<p><a href="<?php echo config_item('base_url').config_item('index_page').'/news/'.$news_item['slug']; ?>">View article</a></p>
...但是我不需要。
有什么想法吗?
使它像这样:
<a href="/news/<?php echo $news_item['slug'] ?>">View article</a>
刚开始就添加斜线
更新:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index\.php|uploads|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
将其添加到应用程序根目录和codeigniter的配置文件中的.htaccess文件中:
$config['index_page'] = ''; //make it like this
现在您不必使用/ index / news,只需从网站根目录使用/ news
因此,您可以像这样使用它:
<a href="/news/<?php echo $news_item['slug'] ?>">View article</a>
它关闭工作
此处可能没有足够的信息来诊断问题。 “不起作用”-什么是错误? 完整网址是什么样的?
它可能与您的Apache和服务器配置有关。 尝试编辑配置,并尝试使用“ PATH_INFO”和“ REQUEST_URI”。
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
最后,(这只是稍微相关),但是在Codeigniter中构建URL的最佳方法是site_url()函数(它创建完整的URL):
echo site_url("news/local/123");
如果您使用以下格式的网址,相对网址将无法正常工作:
原因是因为相对URL使用完整的URI路径作为参考(因此为“相对”)。 因此,如果在/stuff/things
的URI路径(请注意没有反斜杠)上引用stuff/things
(注意前面的斜杠),则会得到/stuff/stuff/things
因为它假定您想要东西在stuff
文件夹中。
我要做的是使用CodeIgniter的site_url()
函数,因为它将为您生成绝对URL(包括域)。
site_url('stuff/things')
将变为http://domain.com/stuff/things
在这种情况下,请使用echo site_url('news/'.$news_item['slug']);
在主播的href中。 你也可以做echo anchor('news/'.$news_item['slug'], 'Link text to this article');
在不编写html的情况下回显文章的链接。
一个警告site_url()
将在URI中包含index.php
(如果尚未从配置文件中将其删除),因此,如果要引用图像,javascript,css等,请使用base_url()
引用您的base_path
配置变量。
编辑:忘记提及,您将需要使用URL Helper才能使这些功能正常工作。
也许为时已晚,但尽管提出了所有建议,但我还是遭受了这个问题的困扰,但问题仍然存在! 现在终于可以用了
$config['base_url'] = '/myrootfolder/';
代替
$config['base_url'] = 'http://localhost/myrootfolder/';
打开您的config.php,然后删除index.php。
然后使用
echo base_url('news').'/'.$news_item['slug']
然后像这样配置您的路线
$route['news/(:any)'] = 'news/index/$1';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.