Moving Kohana to a non public directory

Kohana, PHP framework

This is the second post in my series on the Kohana php framework.  For more, see:

Part 1: Getting started with the Kohana php framework

One of the simplest, and most basic security precautions that you can take is to move your application’s files into a non-public area of your webhost. Having your applications code and configs sitting there in your document root is just never a good idea. An attacker could very easily gain access to the source code of your application, as well as configuration. Next thing you know, there’s empty beer cans all over your apartment and the silverware’s missing. In general, this applies to any kind of web based application, but I’m going to be dealing specifically with Kohana, as part of my series on Getting Started with Kohana.

The first step is to set up your web host. I’m not going to get into details of how to do this, as your mileage may vary. I’m using a pretty vanilla apache, and this is the virtual host config that I’m using:

<VirtualHost *:80>
DocumentRoot /home/rhibbitts/webhosts/site1/public/
<Directory /home/rhibbitts/webhosts/site1/public/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>

Basically, I have a “public” directory set as the document root for my site. This is going to allow me to consolidate any files that need to publicly accessible while putting the applications main files somewhere else. Go ahead and create the `/public/` directory inside your document root. I also usually create an “assets” directory to hold css, javascript, images, etc…

mkdir -p public/assets/images public/assets/css public/assets/js

Outside the document root, I create a “kohana” directory to hold the framework and my actual application files. This directory won’t be accessible from the web. The directory structure for your site should now look something like this:

site
-kohana
--application
--modules
--system
-public
--assets
---js
---css
---images
Kohana file structure

File structure for a new kohana installation

The next step is move index.php and example.htaccess from the kohana directory to “public”. Go ahead and rename example.htaccess to just .htaccess. Now, all you need to do is restart apache.

apachectl restart

Now when you navigate to http://localhost/site, you should see the normal “hello, world!” displayed by the kohana default controller. The difference here is that the request is being routed through your public directory, and the rest of the application is now inaccessible to the public web.