Search code examples
url-rewritinglighttpd

Lighttpd url.rewrite


I wanted all my .php files in my /framework/ folder to be accessed without the .php extension. After scouring the web for a while, I found this:

    url.rewrite = ( 
  "^/framework/([^?]*)(\?.*)?$" => "$1.php$2",
)

But of course there were consequences to that, so now if I access /framework/ (localhost/framework/) it doesn't load the index.php file (localhost/framework/index.php). Instead, it gives a 404.

How do I make it so that any folder beyond and @ /framework/ to load the directories index.php file?

So like

localhost/framework/controller/

would be

localhost/framework/controller/index.php

etc.

I'm rather new to this, so if you could explain to me what you did, that would be great. As you can see I'm not the best with regex.


Solution

  • Add a rule specifically for paths with a trailing slash:

    url.rewrite = (
      "^/framework([^?]*/)(\?.*)?$" => "/framework$1index.php$2",
      "^/framework/([^?]*)(\?.*)?$" => "/framework/$1.php$2"
    )
    

    And here's a breakdown of how the regular expression works:

    ^          // Match the beginning of the string
    /framework // Match any string starting with "/framework"
    (          // Open the first group ($1 in the right hand side)
      [^?]*    // Match zero or more characters that are not '?'
      /        // Ending in '/'
    )          // Close the first group
    (          // Open the second group ($2)
      \?       // Match a '?'
      .*       // Match zero or more characters
    )          // Close the second group
    ?          // Match the second group exactly once or not at all
    $          // Match the end of the string