Beauty’s where you find it
14 Apr
I recently had the need to set up some permanent redirects for an application built on CakePHP. My first thought was to use a simple .htaccess Redirect at the top of my www .htaccess file, like such:
Redirect 301 /foo /bar
However, the result of the redirect was actually the following url:
http://foobar.com/bar?url=foo
This has to do with the QSA flag in the last RewriteRule of the root htaccess file. The QSA flag indicates that a query string should be appended to the url. In our case, foo is recognized as the query string and it ultimately is appended at the end of the bar redirect. Not what I wanted, as the appending of foo to bar results in a 404 error.
My next thought was to set up a RewriteRule for foo, so that it would be redirected to bar. Here is what I came up with, with its exact placement in the default CakePHP webroot htaccess file. The really important thing here has to do with the placement of the rule:
RewriteEngine On
#rule to redirect foo to bar
RewriteRule ^foo$ /bar [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
As you can see here, I am using the R and L flags at the end of the RewriteRule. These flags serve the following purpose:
R: Forces a redirect to the new url, and loads the new page
L: Ensures that this is the last rule that is processed by the server in this file. This is important here, as without the L flag the server would move on to the last rewrite rule, essentially ignoring the R flag for our redirect rule, and it would end up generating a 404 error.
Here’s a great set of cheatsheets if you’re interested in reading more.
Of course there are other options for redirects, including meta refresh or PHP header, however I didn’t want to clutter up the directory with pages whose only purpose was that of setting up a redirect.
Leave a reply