Mod_rewrite to replace extensions?
August 13, 2008 1:15 AM   RSS feed for this thread Subscribe

I need to figure out how to use mod_rewrite to trim the extensions of all of a certain type of file (.php) and replace them with a forward slash

I need to figure out how to use mod_rewrite to trim the extensions of all of a certain type of file (.php) and replace them with a forward slash. I've been hunting on the net for information and poking around in the regex docs, but this one still escapes me.

I want my sites files that look like
"www.domain.com/page.php"
to look like
"www.domain.com/page/"

I know I can write RewriteRules to do that to individual pages, but how do I make it work on all without updating the .httaccess?
posted by SECONDHANDSMOTE to computers & internet (4 comments total) 3 users marked this as a favorite
RewriteRule (.*)\.php$ $1\/

The $ at the end of php anchors the pattern comparison to the end of the URL -- basically, if the URL ends in .php, it will match and apply the rule.

Note, this will also replace URLs like:

example.com/website/subdirectory/foo.php

with

example.com/website/subdirectory/foo/

You may want to be somewhat more restrictive in your rule, perhaps matching only filenames in that directory. For that, you'd use...

RewriteRule ([a-zA-Z0-9_]+)\.php$ $1\/
posted by cheaily at 2:00 AM on August 13, 2008 [2 favorites]


Do you want the URL the user enters to have the slash, but the actual page is PHP? If so, cheaily has the right idea but the wrong way round. Try something like this (off the top of my head, so may be wrong):
RewriteRule ^(.+)/$ $1.php [L]

However, I'd advise you to replace the first . with something more restrictive (as cheaily mentions) to ensure it can't be abused. If you need to run other rules omit the [L]
posted by malevolent at 2:39 AM on August 13, 2008 [2 favorites]


Great idea. URLs are forever, and if you think you'll be using PHP in ten years, you're crazy.

I assume you have MultiViews on, yes?

What you need to know, SHS, is that (.*) matches (nearly) any string, and captures it, and $1 represents later what you captured.
posted by cmiller at 6:13 AM on August 13, 2008


d'oh -- you're right, malevolent... whoops!
posted by cheaily at 8:00 AM on August 13, 2008


« Older Lately, I've been coming home ...   |   Stinky Filter: Please help me ... Newer »
This thread is closed to new comments.