我在CodeIgniter / MAMP Pro中遇到了一个奇怪的路径问题。我通过在$config['index_page'] = '';
中设置config.php
并将以下内容添加到.htaccess
,在CodeIgniter中启用了不错的网址(从网址隐藏了index.php):
RewriteEngine on
RewriteCond $1 !^(index\.php|images|js|css|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
我的应用程序工作正常,但由于某种原因我无法点击我的CSS和JS文件。如果我输入http://mysite:8888/js/jquery.js
,我会收到CodeIgniter 404页面。有什么可能出现这种情况的想法吗?
答案 0 :(得分:2)
我将此.htaccess用于MAMP上的CodeIgniter项目。它也支持子文件夹:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
.htaccess
文件是动态读取的,不需要重新启动MAMP,除非你调整了apache的设置文件。
robots.txt
并不是真正的秘密文件,因此掩盖它并不重要。
脚本/图像/等。文件夹你应该只添加一个index.html
文件,就像CodeIgniter在它的系统文件夹中一样。这样用户无法浏览这些文件夹。不要忘记将index.html文件复制到子文件夹中。这可能看起来很脏,但比使用更多规则使htaccess
更整洁更清晰。
答案 1 :(得分:0)
我认为上面的答案很好,但由于CI是动态编写URL,我更喜欢这种方法。另外,我认为这有助于编写更好的模板代码。 (我在MAMP上专门对此进行了测试。)
例如,将.htaccess文件设置为以下内容:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|assets|robots\.txt)
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
在application/helpers
中创建新助手。我称之为assets_helper.php
,但称之为有用的。将此代码放在该帮助文件中:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('asset_url()')) {
function asset_url() {
echo base_url().'assets/';
}
}
将助手添加到config/autoload.php
la
$autoload['helper'] = array('url', 'assets');
(您可能尚未激活url
助手,但这很常见。)
并为资产文件夹添加路径(在config/routes.php
中):
$route['assets/(:any)'] = 'assets/$1';
现在,当您想要添加css,js或图像时,只需将<? assets_url(); ?>
放在模板代码中即可。
<img src="<? asset_url(); ?>images/logo.png" width="100" height="100" />
或
<link rel="stylesheet" href="<? asset_url(); ?>css/house.css">