Zend Framework URL Rewriting in IIS6

I've written before about URL rewriting with IIS7's URL Rewrite module.

IIS6, which ships with Windows Server 2003 does not have this module though and guess which version my client's IT dept run? As usual, they wouldn't install ISAPI_Rewrite or one of the other solutions for me. In the past, I've simply written a new router that creates URLs with normal GET variables, but this is ugly and I wanted better.

One thing IIS6 does let you do is configure a URL to be called upon a 404 error, which then allows you to have "pretty" URLs and be able to route them.

Firstly, I set up the URL handler in the IIS Manager:

Screen shot 2009-11-13 at 07.46.59-1.jpg

This will result in all unrecognised URLs being redirected to index.php. The standard Zend_Controller_Request_Http object will automatically extract the URL and routing works as expected.

However, there are three problems:

  1. The $_POST array is always empty
  2. $_SERVER['REQUEST_METHOD'] is always GET, even for a post request
  3. The first key in $_GET has been mangled by IIS

As Zend Framework wraps up the request into a Request object, this is fairly simple to work around by creating our own Request object.


class App_Controller_Request_Iis404 extends Zend_Controller_Request_Http
{
    /**
     * Constructor
     *
     * If a $uri is passed, the object will attempt to populate itself using
     * that information.
     *
     * @param string|Zend_Uri $uri
     * @return void
     * @throws Zend_Controller_Request_Exception when invalid URI passed
     */
    public function __construct($uri null)
    {
        // As Zend_Controller_Request_Http accesses the superglobals directly, we
        // will have to write into $_GET and $_POST directly

        // The post variables can be accessed from php://input
        $input file_get_contents('php://input');
        if (strlen($input)) {
            $input urldecode($input);
            parse_str($input$_POST);
        }
        
        // fix $_GET
        foreach ($_GET as $key=>$value) {
            if (substr($key04) == '404;') {
                // special key created by IIS - the actual key name is after the ?
                $bits explode('?'$key);
                if (count($bits) > 1) {
                    $_GET[$bits[1]] = $value;
                }
            }
        }
        
        return parent::__construct($uri);
    }
    
    /**
     * Return the method by which the request was made
     *
     * @return string
     */
    public function getMethod()
    {
        if (!empty($_POST)) {
            return 'POST';
        }
        
        return parent::getMethod();
    }
}

We start by reading the php://input stream which on a POST request will hold the POST variables. We can then transfer them to the $_POST array. Similarly, the key in the $_GET array that has been mangled, is easy to detect as it starts with '404;'. We can then find the ? and the part after it is the real key, so we create a new $_GET element for that item. Finally, we override getMethod() and return 'POST' if there are any elements in $_POST.

To use a custom Request object, you need to create an _init method in your Bootstrap:


class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    function _initIis404RequestObject()
    {
        $this->bootstrap('frontController');
        $frontController $this->getResource('frontController');
        $frontController->setRequest($options['frontController']['requestClass']);  
    }

Zend Framework's standard URLs now work nicely with IIS6 on Window Server 2003.

11 Responses to “Zend Framework URL Rewriting in IIS6”

  1. 1 Rob Allen’s Blog: Zend Framework URL Rewriting in IIS6 | Webs Developer

    [...] Allen has posted a look URL rewriting in IIS 6 (similar to mod_rewrite in Apache) without the URL_Rewrite module that comes [...]

  2. 2 HectorBenitez.com [Blog] » Blog Archive » URL Rewrite en IIS 6

    [...] ve menos profesional y complica un poco el trabajo de los buscadores), sin embargo, he dado con un artículo de Rob Allen en el cual nos brinda una posibilidad extra: Usando una caracteristica de IIS6 para dirigir los [...]

  3. 3 Lee Neilson

    You can always use this.

    http://iirf.codeplex.com

    Works a charm and is free!

  4. 4 Rob...

    Lee,

    You assume that the client's IT dept will let you install iirf :)

    Regards,

    Rob...

  5. 5 Lee

    Indeed :o)

  6. 6 UNi

    Hi,

    thanks for this tutorial, i'm starting to use Zend framework but i has the same problem for my projects.

    I just need an explanation about App_controller_request_iis404. where do you place this code ?

    Thanks for your answer !

  7. 7 Rob...

    UNi,

    library/App/Controller/Request/Iis404.php

    Regards,

    Rob...

  8. 8 Lawrence

    Hi,

    This does not work when submitting forms with a file i.e. when uploading files.

    Does anyone know how to change this so that it works for file uploads?

    Thanks in advance.

    Regards,
    Lawrence.

  9. 9 Rob...

    ah yes. I was gonna update about this. It's a nuisance.

    I ended up setting module, controller and action params in my form as hidden fields and then hacking like this in index.php:

    
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']== 'POST') {
        if(isset($_SERVER['REQUEST_URI']) && strstr($_SERVER['REQUEST_URI'], 'index.php')) {
            $module = isset($_POST['module']) ? $_POST['module'] : 'site';
            $controller = isset($_POST['controller']) ? $_POST['controller'] : 'index';
            $action = isset($_POST['action']) ? $_POST['action'] : 'index';
            
            $baseUrl substr($_SERVER['REQUEST_URI'], 0strpos($_SERVER['REQUEST_URI'], '/index.php'));
            $_SERVER['HTTP_X_REWRITE_URL'] = "$baseUrl/$module/$controller/$action";
        }
    }
    
    

    It's not elegant though.

    Rob...

  10. 10 Lawrence

    Hi Rob,

    Thanks for your quick reply.

    I can't seem to get this to work. My index.php is based on the "Quickstart" version on the Zend Documentation site - could this have an impact? The reason I mention this is because I have seen vastly different index.php files being defined. My index.php looks like this:

    bootstrap()
    ->run();

    PS: I am a total Zend newbie.

    Regards,
    Lawrence.

  11. 11 Lawrence

    Sorry, some of the code seemed to be missing in my previous paste:
    ----------------------------------

    defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

    // Define application environment
    defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));

    // Ensure library/ is on include_path
    set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
    )));

    /** Zend_Application */
    require_once 'Zend/Application.php';

    // Create application, bootstrap, and run
    $application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
    );

    $application->bootstrap()
    ->run();

The views expressed in these comments are not the views of the publisher. However, we believe in the rights of others to express their legitimate views and concerns. Any legitimate complaint emailed to rob@akrabat.com will be seriously considered and the post reviewed as desirable and necessary.

Leave a Reply

Buy now!