5

I'm coding a small CMS to get a better understanding of how they work and to learn some new things about PHP. I have however come across a problem.

I want to use mod_rewrite (though if someone has a better solution I'm up for trying it) to produce nice clean URLs, so site.com/index.php?page=2 can instead be site.com/tools

By my understanding I need to alter my .htaccess file each time I add a new page and this is where I strike a problem, my PHP keeps telling me that I can't update it because it hasn't the permissions. A quick bit of chmod reveals that even with 777 permissions it can't do it, am I missing something?

My source for mod_rewrite instructions is currently this page here incase it is important/useful.

Teifion
  • 108,121
  • 75
  • 161
  • 195

2 Answers2

10

One approach is to rewrite everything to a handling script

RewriteEngine on
RewriteBase /

# only rewrite if the requested file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-s 

# pass the rest of the request into index.php to handle     
RewriteRule ^(.*)$ /index.php/$1 [L]

so if you have a request to http://yourserver/foo/bar/

what you actually get is a request to http://yourserver/index.php/foo/bar - and you can leave index.php to decide what to do with /foo/bar (using $_SERVER['PATH_INFO'] -tom)

You only need to modify .htaccess the first time. All future requests for inexistent files can then be handled in PHP.

You might also find the docs for mod_rewrite useful - but keep it simple or prepare to lose a lot of sleep and hair tracking down obscure errors.

Community
  • 1
  • 1
Ken
  • 77,016
  • 30
  • 84
  • 101
  • 1
    It might be worth explaining that you can get the '/foo/bar' from something like $_SERVER['PATH_INFO'] – Tom Haigh Nov 05 '08 at 22:29
2

Your PHP should for very obvious reasons not be able to modify .htaccess. Even if you get that to work, I'm not sure if it is wise.

How about using a more abstract setup in regard to mod_rewrite rules? Define your general URL pattern, as you would like to use it. For example:

/object/action/id

Then write a set of rules that reroute HTTP requests to a PHP page, which in turn makes the decision what page is to run (say, by including the relevant PHP script).

RewriteRule ^/(\w+)/?(\w+)?/?(\d+)?$ /index.php?object=$1&action=$2&id=$3 [nocase]

This way you would not have to update .htaccess very often an still be flexible.

Tomalak
  • 332,285
  • 67
  • 532
  • 628