1

我在 CodeIgniter/MAMP Pro 中遇到了一个奇怪的路径问题。我在 CodeIgniter 中启用了不错的 URL(从 URL 中隐藏 index.php),方法是设置$config['index_page'] = '';config.php添加以下内容.htaccess

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 页面。知道为什么会这样吗?

4

2 回答 2

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这可能看起来很脏,但比用更多规则弄乱你的东西要干净得多。

于 2013-03-06T16:29:31.473 回答
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

$autoload['helper'] = array('url', 'assets');

(您可能尚未url激活助手,但它很常见。)

并为 assets 文件夹添加一个路由(in 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">
于 2014-03-27T03:33:14.620 回答