Any solution will rely heavily on RewriteCond. You check %{HTTP_HOST} for a leading "www.", and you can use the "-d" and "-f" to test for directories and files, respectively.
Try this:
Code:
RewriteEngine on
# external redirect; we want the visitor to see that "www." is removed
RewriteCond %{HTTP_HOST} ^www.(.*) [NC]
RewriteRule (.*) http://%1/$1 [R=301,L]
# internal redirect. Don't want visitor to see "/script.php?"
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/$1 !-f
RewriteCond %{DOCUMENT_ROOT}/$1.html !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php !-f
RewriteRule ^/?([^/]+)/? /script.php?p=$1 [L,QSA]
If you want to capture a longer path, you'll have to change the pattern in the last line. If you want to skip files with other extensions, add RewriteConds similar to the last few.
Note that you should keep the two task (removing "www.", adding "script.php?p=") separate, as you want visitors to see the first but not the second.