mod_rewrite helo

jason32

New Member
Messages
5
Reaction score
0
Points
0
I need help!

I want to redirect http://mysite.com/whatever to http://mysite.com/script.php?p=whatever but ONLY if http://mysite.com/whatever doesn't exist. I'd also (if possible) like to make sure that no trailing "/" is included, in other words http://mysite.com/frrp/ should redirect to http://mysite.com/script.php?p=frrp

I know that mod_rewrite can do (at least most of) this stuff, but that's as far as my knowledge on the subject goes. I have no idea how to write the rule I need to do this.

Secondly, I'd like to remove the www. prefix from addresses if a visitor includes it, and redirect http://www.mysite.com to http://mysite.com, regardless of the rest of the path. This is less important, but since I'm asking about mod_rewrite this seemed like a good time to ask!

Thanks in advance for your help!
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
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.
 
Last edited:

jason32

New Member
Messages
5
Reaction score
0
Points
0
Thanks so much mission, this is EXACTLY what I wanted, and you've really helped me out. In fact it's better than what I had in mind - I didn't even know it was possible to hide the result of the redirect from visitors like this.

:biggrin:

Some day I'll learn regular expressions, but for right now they're a bit of a mystery to me.
 
Top