I am getting some difficulties with a mod_rewrite rule. I must make 2 kinds of links (the first is perfect for the performers with an album, the 2nd the first is the for those that don't): 1) /lyrics/artist-title/album-title/song-title.php 2) /lyrics/artist-title/song-title.php

My code appears like this:

RewriteRule ^lyrics/(.*)/(.*)/(.*).php$ /artists-lyrics.php?a=$1&b=$2&c=$3 [QSA,L]
RewriteRule ^lyrics/(.*)/(.*).php$ /artists-lyrics.php?a=$1&b=$2 [QSA,L]

Sadly, just the first rule works. How do i change them to be able to make sure they are both work?


You have to build your pattern more specific. Use [^/]+ (a number of figures except /) rather than .* (any figures associated with a length):

RewriteRule ^lyrics/([^/]+)/([^/]+)/([^/]+)\.php$ /artists-lyrics.php?a=$1&b=$2&c=$3 [QSA,L]
RewriteRule ^lyrics/([^/]+)/([^/]+)\.php$ /artists-lyrics.php?a=$1&b=$2 [QSA,L]

The 2nd rule never works, since the first rule matches "/lyrics/artist-title/song-title.php" aswell: (.*) means: a variety of figures (even zero).

Without getting the chance to check it, this might work:

RewriteRule ^lyrics/([^\]+)/([^\]+).php$ /artists-lyrics.php?a=$1&b=$2 [QSA,L]
RewriteRule ^lyrics/([^\]+)/([^\]+)/([^\]+).php$ /artists-lyrics.php?a=$1&b=$2&c=$3 [QSA,L]

Generally you need to set your atom as limited as you possibly can to prevent unintentional effects. Within the example below, only alphanumeric figures are recognized (that is most likely what you would like). The + sign denotes a number of, whereas * denotes zero or even more.

RewriteRule ^lyrics/([a-z0-9]+)/([a-z0-9]+)/([a-z0-9]+).php$ /artists-lyrics.php?a=$1&b=$2&c=$3 [QSA,L]
RewriteRule ^lyrics/([a-z0-9]+)/([a-z0-9]+).php$ /artists-lyrics.php?a=$1&b=$2 [QSA,L]