i just want to internally rewrite the url from something like http://www.example.com/item?title=titlename&id=5
and http://www.example.com/page?title=titlename
to something like this: http://www.example.com/item/titlename/5
or http://www.example.com/page/titlename
.
That should be the other way round... internally rewrite from http://www.example.com/item/titlename/5
to http://www.example.com/item?title=titlename&id=5
. And presumably you should be including the .php
extension on the target URL? (Don't rely on another directive to do append the file extension.)
Try something like the following:
Options -MultiViews
RewriteEngine On
RewriteRule ^([a-z]+)/([\w-]+)(?:/(\d+))?$ /$1.php?title=$2&id=$3 [L]
This will handle a URL both with and without the trailing ID (eg. /5
). However, if you specify a URL of the form /item/titlename
(ie. no numeric id), then you will naturally get an empty id
URL parameter passed to your script.
Note that MultiViews
must be disabled for this to work, otherwise mod_negotiation will rewrite the URL from item
to item.php
(for example) before mod_rewrite and you won't get the URL parameters passed.
If you specifically need to check that the target file, eg. page.php
exists before rewriting then you can include an additional condition to check this. However, I wouldn't have thought this was necessary since you'll get a 404 regardless and checking that the file exists is relatively expensive.
Options -MultiViews
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([a-z]+)/([\w-]+)(?:/(\d+))?$ /$1.php?title=$2&id=$3 [L]
This assumes that your files exist in the document root of your site.
Just to clarify, as mentioned in comments, you should already be linking to URLs of the form http://www.example.com/item/titlename/5
in your application.