WordPress Rewrites without .htaccess

It’s been known for many years that apache’s AllowOverride .htaccess files incur a performance hit, as every node on the path from the location hit to the document root need to be checked for .htaccess files and parsed. I’ve mostly avoided the whole issue by hosting on nginx instead, but I recently needed to host WP on Apache again and ran into this issue. Many places offer a snippet like this for rewrites from a .htaccess file:

RewriteEngine On
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [NC,L]

This says:

  • If the request is for index.php, serve it as is.
  • If the request is for a file or folder that does not exist, serve index.php instead.
  • Implicitly, if the request is for a file or directory that does exist, serve that.

The problem is that while this will work in a .htaccess file, it won’t work in main apache config because REQUEST_FILENAME will just be a filename, not a whole path, so it’s unlikely to match. The solution to this is to prepend the document root:

RewriteEngine On
RewriteRule ^index.php$ - [L]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [NC,L]

This took me a silly amount of time to solve. I found the critical info in this post, but I thought I’d clarify it here. HTH!

Leave a Reply