I want to mod_rewrite this Url:
Before:
website.altervista.org/page.php?name=value
After:
website.altervista.org/value
I want to mod_rewrite this Url:
Before:
website.altervista.org/page.php?name=value
After:
website.altervista.org/value
Solution:
RewriteCond %{REQUEST_URI} !page.php$
RewriteRule ^(.+)$ /page.php?name=$1 [L]
Explanation:
The mod_rewrite RewriteRule
has 3 parameters:
Implemented as such:
RewriteRule pattern substitution [flags]
Starting at server root, enter the requested URL path in the RewriteRule
"pattern" parameter, and the desired path in the "substitution" parameter. In this case:
RewriteRule ^(.+)$ /page.php?name=$1 [L]
If the URL varies and you don't want to (or can't) write a rule for every situation then use the regular expression ^(.+)$
to capture the dynamic value and inject it into your substituted path using the RE capture variable $1
. The first set of parenthesis is $1
, the second set is $2
, etc. And capturing parenthesis can be nested.
^(.+)$
This regular expression can be read as: ^
at the start of the string, $
all the way to the end of the string, look for .
any character +
one or times and ()
capture that value into a variable.
Problem:
Even though we have the flag [L]
(last rule evaluated), the mod_rewrite engine (behind the scenes) sends the newly constructed request /page.php?name=somevalue
back through the mod_rewrite engine until no rules are met or, apparently, there are no changes to the request. Fortunately there is a supplimentary directive to expand on the conditional power provided by the RewriteRule
called RewriteCond
.
The mod_rewrite RewriteCond
applies to the next occurring RewriteRule
and also has 3 parameters:
The Test String can be derived from a few sources. Often a Server Variable, relating to the current request, is used here as the subject of this condition.
The Conditional Pattern is, again, text or a regular expression, but has some additional special conditions that may be evaluated. Read the Apache online mod_rewrite documentation for a detailed explanation.
In this case: RewriteRule ^(.+)$ /page.php?name=$1 [L]
, our newly substituted request is sent back through mod_rewrite as /page.php?name=somevalue
and matches our "catch-all" rule, therefore our original "somevalue" is lost and replaced with our newly requested resource page.php
. To prevent our "catch all" from catching our "page.php" requests let's exclude it from the rule using RewriteCond
.
RewriteCond %{REQUEST_URI} !page.php$
RewriteRule ^(.+)$ /page.php?name=$1 [L]
This RewriteCond
can be read as: %{REQUEST_URI}
get the requested resource and does it !
NOT $
end with page.php
. If this condition is true, continue to the next condition or rule. If this condition is not true, skip this rule set and continue to the next rule set.