Wednesday, October 5, 2011

Wordpress htaccess

One of my friends recently had a desire to rewrite some URLs with a Wordpress installation. The theme they were using was called Solid-WP and it supported a concept called "Projects". When you create a new project it actually gives it the URL

http://www.example.com/project/

However there was a requirement that the URL should be renamed to http://www.example.com/apps/.

To do this I broke out mod_rewrite. Wordpress has some default rewrites stored inside .htaccess. Here is what it looks like:

# BEGIN WordPress

RewriteEngine On

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


# END WordPress


Rewrite can be hard to understand so I wanted to breakdown exactly what Wordpress was doing. First line turns on the Rewrite engine and 2nd line is used to define a base URL for rewrites.


RewriteRule ^index\.php$ - [L]

If there is a request for /index.php then don't do any rewriting and just end processing right here (the L flag).

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

These rewrite conditions are to test for real files and directories. Basically we don't want to rewrite a URL if the URL points to a directory or file. We just want to serve the file up. !-f tests whether or not the file exists and !-d tests whether or not the directory exists.

RewriteRule . /index.php [L]

This last line as I understand it rewrites all requests to index.php.

What I ended up adding was this:


RewriteEngine On

RewriteRule project/(.+) /apps/$1 [L,R]
RewriteRule apps/(.+) /example-wp/index.php/project/$1/ [L]

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


The first time a user might hit /project/example. They would hit the first rule and get redirected. Processing would stop.

The second time a user hit the URL it would say /apps/example which would trigger the 2nd rule. It would get rewritten to the long form of WordPress's controller action.

No comments: