views:

29

answers:

2

I am trying to get mod_rewrite to work with my site but for some reason it's not working. I've already entered code into my .htaccess file to redirect non-www to www so I know mod_rewrite is working in general.

The url's I'm trying to change are example.com/index.php?p=home so the new URL would be example.com/page/home

However, when I try this code I simply get a 404 telling me that /page/home doesn't exist.

Options +FollowSymLinks

RewriteEngine on

RewriteRule index/p/(.*)/ index.php?p=$1
RewriteRule index/p/(.*) index.php?p=$1

Can anyone help me out please?

+2  A: 

Your rewrite rule uses index/p/xxxxx but you want /page/xxxx

try

RewriteRule ^/page/(.*)/ index.php?p=$1
RewriteRule ^/page/(.*) index.php?p=$1
rikh
This is what I was supposed to put in my original post. Sorry for the confusion.
kaotix
+1  A: 

Your pattern doesn't match your example URL. Assuming your example URL was correct, you wanted this instead:

Options +FollowSymLinks

RewriteEngine on

# We want to rewrite requests to "/page/name" (with an optional trailing slash)
# to "index.php?p=name"
#
# The input to the RewriteRule does not have a leading slash, so the beginning
# of the input must start with "page/". We check that with "^page/", which
# anchors the test for "page/" at the beginning of the string.
#
# After "page/", we need to capture "name", which will be stored in the
# backreference $1. "name" could be anything, but we know it won't have a
# forward slash in it, so check for any character other than a forward slash
# with the negated character class "[^/]", and make sure that there is at least
# one such character with "+". Capture that as a backreference with the
# parenthesis.
#
# Finally, there may or may not be a trailing slash at the end of the input, so
# check if there are zero or one slashes with "/?", and make sure that's the end
# of the pattern with the anchor "$"
#
# Rewrite the input to index.php?p=$1, where $1 gets replaced with the
# backreference from the input test pattern
RewriteRule ^page/([^/]+)/?$ index.php?p=$1
Tim Stone
This works perfectly. I think the ([^/]+)/?$ fixes it. Could you explain the parts of that expression so I can better understand it please?
kaotix
@kaotix - I added comments to the rule now. I wasn't sure how familiar you were with regular expressions in general, so I tried to explain in as much detail as I could.
Tim Stone