Remove index.php from your URL | Rob Allen's DevNotes

:

One thing you may have noticed with Zend Framework projects that use the baseUrl() view helper to reference CSS and other static files is that it doesn't work if the URL contains contains index.php.

Let's explain, by using code from the tutorial.

In the layout.phtml file, we link to a CSS file like this:

<?php echo $this->headLink()->prependStylesheet($this->baseUrl().'/css/site.css'); ?>

This code uses a baseUrl() view helper that looks like this

<?php
class Zend_View_Helper_BaseUrl
{
function baseUrl()
{
$fc = Zend_Controller_Front::getInstance();
return $fc->getBaseUrl();
}
}

When you go to http://localhost/zf-tutorial/ you get an page that looks like this:

Screen short of Zend Framework tutorial

However, if you go to http://localhost/zf-tutorial/index.php, you get this:

zf-tutorial_no_css.jpg

This happens because the baseURL used in the href of the CSS link in the second case is /zf-tutorial/public/index.php/css/site.css rather than the correct /zf-tutorial/public/css/site.css.

Solution using mod_rewrite

One way to fix this is to use a mod_rewrite rule in your .htaccess file:


RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /([^/]+/)*index.php
RewriteRule ^index.php(.*)$ /zf-tutorial/public$1 [R=301,L]

I did have to put the full subdirectory into the rewrite rule to get it to work.

The quick and dirty solution

At the top of your index.php file take out the index.php from the REQUEST_URI:

$_SERVER["REQUEST_URI"] = str_replace('index.php','',$_SERVER["REQUEST_URI"]);

This obviously works, but feels a bit "hacky"! There's probably other ways to solve it too, but once I found the rewrite rule, I stuck with it.