PHP Framework Side-by-Side with WordPress

I was working on a website this week where I wanted to use WordPress so the client could benefit from its CMS and blogging capabilites, but also wanted to use a PHP framework to handle some custom programming. Compared to WordPress, almost any PHP framework is going to be easier to do custom programming with. But what about routing? How will the website know what to route to the framework, and what to route to WordPress?

.htaccess to The Rescue

# Turn off directory indexing
Options -Indexes

# Turn on URL rewriting and set base
RewriteEngine On
RewriteBase /

# Remove WWW
RewriteCond %{HTTP_HOST} !^foo\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ http://foo.com/$1 [L,R=301]

# Deny requests to specific directories
RewriteRule ^(app|tests|vendor) - [F,L]

# URLs routed to PHP Framework
RewriteRule ^$ /framework_index.php [L]
RewriteRule ^index\.php$ /framework_index.php [L]
RewriteRule ^abc.*$ /framework_index.php [L]
RewriteRule ^def.*$ /framework_index.php [L]
RewriteRule ^ghi$ /framework_index.php [L]
RewriteRule ^jkl$ /framework_index.php [L]
RewriteRule ^mno.*$ /framework_index.php [L]

# If file or directory does not exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Route to WordPress
RewriteRule .* wp_index.php/$0 [PT,L]

Notice something, that I renamed my framework’s index.php file to framework_index.php, and the WordPress index.php file to wp_index.php. Since my framework is handling the generation of the home page, there is a RewriteRule for that, but there also has to be a RewriteRule for index.php! Without the RewriteRule for index.php, I just got a bunch of 404 errors.

I know I could have demonstrated what I did with less code, but I wanted to show how and where I handled such things as:

  • Only allow non WWW prefixed URLs.
  • Deny access to app, tests, and vendor directories.
  • Allow access to assets and other files that actually exist.
  • Turn off directory indexing.