views:

16

answers:

2

Using Apache on a Red Hat server, I'm trying to rewrite the URL of a member's store on our website from:

domain.com/store.php?url=12345

to:

domain.com/12345

Using these rules, I can get it to work if I always remember to add an ending slash:

Options -Indexes 
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^store/url/(.*)$ store.php?url=$1
RewriteRule ^(.*)/$ store.php?url=$1

domain.com/12345/ works, but domain.com/12345 does not work.

Removing the slash in the last line of Rewrite code breaks a lot of stuff. Is there a way to get this to work both with or without that ending slash?

A: 

What if you made the slash optional? Furthermore, you probably to to specify something more specific than (.*), because domain.com/a/b/c/d/e will match. Instead, you can use a negated character class to specify everything other than a slash.

RewriteRule ^([^/]*)/?$ store.php?url=$1

Alternately, if you only want to capture numbers, you can use the \d shorthand class (which matches any digit) along with a + which specifies that at least one digit must be present:

RewriteRule ^(\d+)/?$ store.php?url=$1
Daniel Vandersluis
Hmmm. Guess this has turned into a more complicated regex. I'm trying for any word character, followed by optional hypens and optional additional word characters. I think the pattern would be:[\w]+[-\w]+?
rwheindl
`\w+(-\w+)*` is probably what you're looking for (assuming you don't want successive dashes). Feel free to start another question if you're having more trouble about another aspect of your rewrite rules.
Daniel Vandersluis
Yes, that's it. Thank you.
rwheindl
A: 

Your attempt using ^(.*)$ fails because that would match any URL path. Use a more specific pattern than .*, maybe \d+ to allow only one or more digits:

RewriteRule ^(\d+)$ store.php?url=$1
Gumbo