Search code examples
phpregexapache.htaccessurl-routing

.htaccess URL rewrite with random parameters


I'm currently writing a PHP app and am about to create various controllers. Currently I have one controller with certain method, so the URL looks like this:

http://somewebsite.com/index.php?c=controller&a=action

It's being rewritten to this:

http://somewebsite.com/controller/action

With this .htaccess file:

RewriteEngine On
RewriteRule ^([a-z]+)/([a-z]+)$ index.php?c=$1&a=$2 [NC]

What I want to achieve is the ability to rewrite URL with more than one controller (the more, the better), possibly in random order. Is there a more convenient way than rewriting every possible combination of URL parameters?


Solution

  • Many frameworks (Codeigniter, WordPress, Laravel, etc.) use an .htaccess file similar to the following:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    

    This rewrites all incoming URLs to be handled by the index.php file. You can then use $_SERVER['REQUEST_URI'] variable to get the exact request URI, parse it, and then handle it how you want.