Skip to content

Instantly share code, notes, and snippets.

@jamesvl
Created April 8, 2011 17:32
Show Gist options
  • Save jamesvl/910325 to your computer and use it in GitHub Desktop.
Save jamesvl/910325 to your computer and use it in GitHub Desktop.
Web server rewrite rules for using klein PHP router

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

@mgip
Copy link

mgip commented May 11, 2020

In case of PHP built-in server on local dev mode, what can i do?

@jamesvl
Copy link
Author

jamesvl commented May 11, 2020

I've never actually used the PHP dev server, but per their docs it looks like basic URL rewriting is already built in:

If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached.

@SudoMati
Copy link

SudoMati commented Jun 28, 2020

In case of PHP built-in server on local dev mode, what can i do?

For anybody wondering, this is the way:
$ php -S localhost:3001 -t ./ ./index.php

Assuming index.php is your bootstrapping file. Run this command from your root dir.

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