What is the purpose of multiple .htaccess files in CakePHP?

|
| By Webner

Purpose of multiple .htaccess files in CakePHP

In Cakephp, contained .htaccess files are as follows:

newcakeproject/.htaccess
/app/.htaccess
/app/webroot/.htaccess

1. newcakeproject/.htaccess

CakePHP root directory .htaccess redirects everything to your CakePHP app (means to webroot). We can also redirect the url to some other url or also redirect the same url to secure one (https://)

Code:

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$ app/webroot/    [L]
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

.htaccess file inside app directory (/app/.htaccess)

CakePHP app directory .htacces again redirects everything to your CakePHP webroot.

Code:

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^$    webroot/    [L]
   RewriteRule    (.*) webroot/$1    [L]
</IfModule>
</pre>

.htaccess file inside webroot directory (/app/webroot/.htaccess)

At this level it just redirects to index page.

Code:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /path/to/cake/app
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/(app/webroot/)?(img|css|js)/(.*)$
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

Sometime, we may need to put cakephp in a sub directory (cake_sub_project) then we have to define RewriteBase and write htaccess in root folder.

Code:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule    ^$ cake_sub_project/app/webroot/    [L]
RewriteRule    (.*) cake_sub_project/app/webroot/$1 [L]
</IfModule>

Follows the same process for htaccess in sub project directories as well.

The Apache module mod_rewrite allows you to rewrite URL requests.

Example: Redirect url to secure url by RewriteRule
Code:

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

So you can say there is only one .htaccess file doing the real work, and that is in webroot directory (which is the file in /app/webroot/.htaccess). This passes any requests that aren’t for an existing file or directory to index.php.

Leave a Reply

Your email address will not be published. Required fields are marked *