I could use a REST from ModRewrite

This blog post is more than 6 years old, so the content may be out of date.

I won't enthuse about the virtues of web-services and especially REST - many people have written great articles and presentations before me :-)

One problem irked me: delivering different content on the same URL using a framework.

I'm building a system which stores data about a company.
You visit company/20 and you get a page with data about company 20.
You POST to company/20 and the system saves the new data.

This can make your controller a little fugly:

else {

Man, that code is ugly. And your controller class balloons because it's handling updates as well as views.

I want to be able to route POSTs to one controller, and views to another. But the framework I'm using doesn't (easily) allow that.

Instead, I'm using mod-rewrite to re-route POSTs to /company/20 to the URL /POST/company/20, and running a different controller on that URL.

Here's the code:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    #This is the additional code to redirect POSTs to a custom URL
    RewriteCond %{REQUEST_METHOD} POST
    RewriteCond $1 !^POST.*$
    RewriteCond $1 !^index.php?.*$
    RewriteRule ^(.*)$ POST/$1 [N,DPI]
    #This is the regular framework code, to route requests via index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

Annoyingly, I found that when you change the URL with a RewriteRule then loop, the %{REQUEST_URI} variable processed by RewriteCond doesn't alter (and the URI processed by RewriteUrl isn't available to RewriteCond). define recursion {recursion};
This hack gets around the problem by making use of capturing brackets on the RequestRule, and a backreference on the RequestCond.

Share and enjoy :-)

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <apache>, <bash>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.