你在这里有两个问题:
您要重写/application/views/...
的规则/views/...
是在将所有内容重写为index.php
. 您需要将更具体的重写放在更通用的重写之前,以防止更通用的重写停止处理。
您的重写规则不完整。您有一个规则,以便请求/application/views/...
被重写,就好像文件实际上位于/views/...
. 但是,由于您实际上仍将文件存储在文件application/views/
夹中,因此您缺少允许您像访问它们一样/views/...
访问它们的规则。
这是您可以制定重写规则以使其正常工作的一种方法。(我省略了重定向/application/views/...
到的规则,/views/...
因为我不明白你为什么需要它 - 只是使/application
不可访问并且只使用/views/...
然后它无论如何都无关紧要。)
RewriteEngine on
# Installation directory
RewriteBase /
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
# Pretend that views are one directory above where they actually are
RewriteRule ^views/(.*) application/views/$1 [L]
# Protect application and system files from being viewed,
# UNLESS we are redirecting to them from another rule
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(?:application|modules|system)\b - [F,L]
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php [PT]
(感谢@CDuv 对mod_rewrite 的回答:允许重定向但阻止直接访问该ENV:REDIRECT_STATUS
技巧。)
实际上,您可能会发现创建指向此内容的路由更有意义。这是因为它允许您将application
、modules
和system
目录移出 Web 根目录。这样做的一个好处是,如果您开发了另一个应用程序,您可以在多个 Kohana 应用程序之间共享modules
和。system
另一个是这意味着您不需要依赖 htaccess 来保护对这些目录的访问。
这是一个基于Kohana 用户指南模块的简单方法,可用于提供这些文件。
将此路线添加到bootstrap.php
:
// Static file serving (CSS, JS, images) - ADD MORE EXTENSIONS IF NEEDED
Route::set('media', 'views(/<file>)', array('file' => '.+\.(css|js|jpg|png)'))
->defaults(array(
'controller' => 'media',
'action' => 'media',
'file' => NULL,
));
添加控制器Controller_Media
:
class Controller_Media extends Controller
{
public function action_media()
{
// Get the file path from the request
$file = $this->request->param('file');
// Find the file extension
$ext = pathinfo($file, PATHINFO_EXTENSION);
// Remove the extension from the filename
$file = substr($file, 0, -(strlen($ext) + 1));
if ($file = Kohana::find_file('views', $file, $ext))
{
// Check if the browser sent an "if-none-match: <etag>" header, and tell if the file hasn't changed
$this->check_cache(sha1($this->request->uri()).filemtime($file));
// Send the file content as the response
$this->response->body(file_get_contents($file));
// Set the proper headers to allow caching
$this->response->headers('content-type', File::mime_by_ext($ext));
$this->response->headers('last-modified', date('r', filemtime($file)));
}
else
{
// Return a 404 status
$this->response->status(404);
}
}
}