Redirect All Requests to Index.php via htaccess

📁 devops

For one of my website projects I wanted to create a very basic content management system. The plan was to have a header and footer template class, and include these from the ‘index.php’. The bit between the header and footer (‘content’) would then be pulled from another file, depending on the URL.

The basic set-up for this kind of CMS is that all requests are sent to one script, which handles working out which files need to be included based on the request URL. If we’re using Apache as our web server, we can do this easily enough using the .htaccess file.

A htaccess file (also known as a distributed configuration file) allows you to configure your web-server on a per-directory basis. One of the handy features of the htaccess file is that we can invoke server-side modules. We can use the mod_rewrite module to redirect or rewrite certain URL requests.

So to set-up our CMS, we need to rewrite all requests to any file on the server to ‘/index.php’. A first attempt at this might be:

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
RewriteRule .* /index.php

This looks OK, until you think about what will actually happen. We’re redirecting ALL requests to ‘index.php’ – including requests to ‘index.php’… They call this infinite loopage in the biz’. Our next (and much better attempt) would be:

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* /index.php

This will work well – unless you have things like images, stylesheets, JavaScript or generally any other files we’ve come to expect in a rich internet experience. We can fix this by also excluding requests to these filetypes from the rewrite:

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*\.css$ [NC]
RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]
RewriteCond %{REQUEST_URI} !.*\.js$ [NC]
RewriteRule .* /index.php

And there you have it! A (useful) .htaccess file used to redirect all requests to the index.php file! Now for that CMS…