Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to match a single reference in a URL to pass to a script, while retaining the rest as the path to the script. For example:

#/scripts/paramater/foo/bar.php should call
RewriteRule ^scripts/([^/]+)/(.*)$ scripts/$2?id=$1 [L,QSA]

However my backreference is matching multiple times. $2 only contains "bar.php" and $1 is somehow repeating for "parameter" and "foo".

How can I prevent the backreference from repeating itself?

Edit: I've narrowed down the problem somewhat by fiddling with the second part of the rewrite rule.

#This doesn't work, as above
#Outputs: scripts/bar.php?id=foo?id=parameter
RewriteRule ^scripts/([^/]+)/(.*)$ scripts/$2?id=$1 [L,QSA]

#This works
#Outputs: foo/bar.php?id=parameter
RewriteRule ^scripts/([^/]+)/(.*)$ $2?project_slug=$1 [L,QSA]

Which confuses me even more! Any help appreciated

share|improve this question
up vote 1 down vote accepted

Easy: add condition that will prevent execution of rewrite rule on already rewritten URL.

I see 2 main approaches (based on your URL examples):

1. Will prevent rewriting if URL was already rewritten by the same rule:

RewriteCond %{QUERY_STRING} !^project_slug=
RewriteRule ^scripts/([^/]+)/(.*)$ scripts/$2?project_slug=$1 [L,QSA]

On initial rewrite iteration URL will be rewritten and query string will have project_slug= at the start of the string. On next iteration the condition will not allow rewriting because query string already starts with project_slug=.

Of course, this approach will not work if original URL (before rewriting) has query string that starts with project_slug= (e.g. /scripts/parameter/foo/bar.php?project_slug=hello) .. which should not happen under normal circumstances (unless someone knows how rewrite rule works and is messing around on purpose).

2. Allow rewrite execution ONLY on first iteration (regardless of which rule has rewritten this URL):

RewriteRule ^scripts/([^/]+)/(.*)$ scripts/$2?project_slug=$1 [L,QSA]

Unfortunately the variable used here %{ENV:REDIRECT_STATUS} is not populated on every Apache build/setup. Therefore it may work fine on your setup but may not on another hosting. Unfortunately I cannot tell you how to determine (configure your Apache) if it will work without executing some sort of rewrite test.

share|improve this answer
Thank you! I didn't realise rewrite rules could run more than once. Your first solution works perfectly – Tak Aug 25 '11 at 20:11

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.