Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created December 3, 2012 00:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rican7/4191715 to your computer and use it in GitHub Desktop.
Save Rican7/4191715 to your computer and use it in GitHub Desktop.
URL Rewriting

URL-rewriting for klein PHP router

Why rewrite URLs? Check Wikipedia

Apache

Make sure AllowOverride is on for your directory, or put in httpd.conf

# Apache (.htaccess or httpd.conf)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /index.php [L] 

nginx

# basics
try_files $uri $uri/ /index.php?$args;

If you're trying to route requests for an app that is not in the document root, invoke klein's dispatch line like this:

<?php
   define('APP_PATH', '/your/webapp');
   dispatch(substr($_SERVER['REQUEST_URI'], strlen(APP_PATH)));
?>

Then in your nginx.conf file, use:

location /your/webapp/ {
   try_files $uri $uri/ /your/webapp/index.php?$args;
}

Don't do this.

# nginx
if (!-e $request_filename) {
    rewrite . /index.php last;
}

See nginx pitfalls.

More Reading

Note: This gist originally here, from chriso and updated based on this from jamesvl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment