[英]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.