'Remove '.php' file extension but still validate paramaters after trailing slash?

I've been searching for how to do this, and I haven't been able to get anything to work yet. I want to remove the '.php' file extension from all files that have it while also adding a trailing slash and validating all the parameters following it. For example, I want my/directory/users/USER_ID/ to function the same as my/directory/users.php/USER_ID/.



Solution 1:[1]

As you reference Apache, here's one way of doing it in your .htaccess:

RewriteEngine On
RewriteRule ^my/directory/users/([0-9]+)/$ my/directory/users.php/$1/ [L]
  • Look for incoming URLs which match the regex ^my/directory/users/([0-9]+)/$.
    • ^ means 'start of the url'
    • $ means 'end of the url'
    • [0-9]+ means 'at least one digit here'
    • The brackets tell it to capture that digit series as a variable. It's the only variable we create, so it'll end up as $1.
  • If we match on that URL, we'll rewrite it to my/directory/users.php/$1/ and then stop considering any other rewrite rules, because this is a [L]ast one.
    • Using the variable $1, the previously captured digit series.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luke Briggs