Entries tagged "Mod Rewrite"

Concrete5 Mod Rewrite to Add Request Trailing Slash

I recently had the need to add a trailing slash to http requests in a Concrete5 application (that did not have pretty urls enabled).  The issue stemed from clients adding links that did not include the trailing slash.  In the interest of keeping things clean, here are the rules I wanted to follow:

  1. Only rewrite urls that contain index.php
  2. Only rewrite urls where the above is satisfied and is followed by at least 1 trailing slash
  3. Only rewrite urls where the above is satisfied and the url ends with at least one valid character (defined below)
  4. Only rewrite urls where the above is satisfield and does not already end with a trailing slash

Read More »

Permanent Redirects and CakePHP

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.

Using a RewriteRule

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.

Other options

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.

Mobify empowers marketers and developers to create amazing mobile web experiences. Tap to learn more

Mobify