1

I'm struggling a bit with mod_rewrite and replacing multiple variables with regexes. I'm trying to rewrite the following:

www.mysite.com/avatars/funny/1

into:

www.mysite.com/avatars.php?genre=funny&page=1

Right now I have the following, which isn't really doing the trick:

RewriteRule ^/avatars/?(.*)/?(.*)$ /avatars.php?genre=$1&page=$2

3 Answers 3

4

The * operator is greedy. This means that it will grab as much as it possibly can.

In your example, the first (.*) block will match /funny/1. The second one will match nothing at all, but that's OK because * matches "zero or more" of the preceding character.

Using a different block to match the parts in between the slashes will do the trick. Something like this:

RewriteRule ^/avatars/([a-z]*)/([0-9]*)$ /avatars.php?genre=$1&page=$2

or this:

RewriteRule ^/avatars/([^/]+)/([^/]+)$ /avatars.php?genre=$1&page=$2

There's also no need for the ? operator after the slashes as in order for there to be two variables, the slashes must be there.


Apache also has reluctant operators which are the opposite of greedy operators. You can use these by adding a question mark after a normally greedy operator. Like this:

RewriteRule ^/avatars/(.*?)/(.*?)$ /avatars.php?genre=$1&page=$2
2
  • Thanks, this solved some issues. However, if I navigate to mysite.com/avatars with this rule, i get a 404.
    – user745595
    May 4, 2012 at 13:44
  • Are you expecting to load the /avatars.php file when you request /avatars ? If so, that might explain what the question marks after the slashes were doing in your original rule. I would go with an extra rewrite rule: RewriteRule ^/avatars/?$ /avatars.php [L]
    – Ladadadada
    May 4, 2012 at 14:20
0

You don't need the ? since the slashes are not optional. However, you probably need to stop processing once this rule is applied ([L]). Can you try the following?

RewriteRule ^/avatars/(.*)/(.*)$ /avatars.php?genre=$1&page=$2 [L]
0

I think your use of /? is the problem, try this:

RewriteEngine on
RewriteRule ^avatars/([^/]+)/([^/]+)$ avatars.php?genre=$1&page=$2 [L]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .