At first look, the way Apache mod_rewrite module deals with query strings can be a little confusing. From the RewriteRule documentation:
qsappend|QSA’ (query string append)
This flag forces the rewrite engine to append a query string part of the substitution string to the existing string, instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.
Let’s try to redirect a page depending on its query string. Our rewrite rule should looks like this:
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^page\.php$ http://mydomain.site/page/%1.php [R=302,L]
According to the official documentation, you would expect the following behavior:
/page.php?id=37 -> http://mydomain.site/page/37.php /page.php?id=40 -> http://mydomain.site/page/40.php # and so on
However, if you don’t append something new, then the original query is passed through the rules unchanged by default.
/page.php?id=37 -> http://mydomain.site/page/37.php?id=37 /page.php?id=40 -> http://mydomain.site/page/40.php?id=40 # and so on
If you want to discard the original query string you must append an empty question mark at the end of the rule. Let’s call it the query string not append or query string discard flag.
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^page\.php$ http://mydomain.site/page/%1.php? [R=302,L]
Here’s a quick reference for dealing with query string in a RewriteRule.
Keep original query (default behavior) RewriteRule ^page\.php$ /target.php [L] # from http://example.com/page.php?foo=bar # to http://example.com/target.php?foo=bar Discard original query RewriteRule ^page\.php$ /target.php? [L] # from http://example.com/page.php?foo=bar # to http://example.com/target.php Replace original query RewriteRule ^page\.php$ /target.php?bar=baz [L] # from http://example.com/page.php?foo=bar # to http://example.com/target.php?bar=baz Append new query to original query RewriteRule ^page\.php$ /target.php?bar=baz [QSA,L] # from http://example.com/page.php?foo=bar # to http://example.com/target.php?foo=bar&bar=baz


Thanks, this post really helped me out.
Thank god for you, I’ve been stuck on this for too long now…
I think there are typos in your otherwise excellent examples?
I think it should be like this (or maybe I’m clueless!):
Keep original query (default behavior)
RewriteRule ^page\.php$ /target.php [L] # NO ? on the end
# from http://example.com/page.php?foo=bar
# to http://example.com/target.php?foo=bar
Discard original query
RewriteRule ^page\.php$ /target.php? [L] # ? on the end
# from http://example.com/page.php?foo=bar
# to http://example.com/target.php # removes the q/s
Hi Mark,
you’re right. Fixed.
Thanks!
Hi,
How can I do it in the reverse for same html? I need to add a parameter to the url.
eg:
https://www.abc.com/test.html
to
https://www.abc.com/test.html?Flag=1
Whew, thanks! About 20 minutes of googling and trying stuff that wasn’t working!
Thanks for sharing!
maj
Hi all,
First, download EzyPal Paypal Shopping Cart script below is you havn’t:
http://rapidshare.com/files/279640968/ezypal157.zip (for study only plz)
After turn on Search Engine Friendly ULRs function (SEF) under Admin CP, EzyPal will rewrite all catalog and account URLs to something likes /_catalog and /_account, and it add underscores between catalog and product names.
This is the rewrite rules:
How to remove underscores from “/_catalog” and “/_account”, and replace others with hyphen?
Thanks.
DONE, a rewrite rules modified version here:
http://rapidshare.com/files/281477176/ezypal157.rar (for study only)
still not perfect, can not get rid of “catalog/” from url like http://localhost/catalog/cataname/prodname.htm
http://localhost/cataname/prodname.htm will be better, who can do this…
Hi
I am writting the below code in httpd-vhosts.conf. but it is not working for me… Can anyone explain me where I am wrong.
RewriteCond %{LA-U:REMOTE_USER} (.+) RewriteRule ^http://%{HTTP_HOST}:8080/seaside/UserLoginPage?userid=%1$ http://%{HTTP_HOST}:8080/seaside/UserLoginPage?[L]Thanks
You should not have to use LA-U in this case, because mod_auth runs before mod_rewrite (on a normally-configured server). If the user is authenticated, then REMOTE_USER will be provided by the client browser on every request.
Also, the first parameter of the RewriteRule can’t be an absolute URL. It must be relative from the current host.
Please let me know if is there any other issue.
Hi
My client wants to redirect query string based redirection on his zen cart, I tried a lot from my side to resolve but fails, please any help from this blog? I will provide original htaccess file and path on email(not here as public area).
Please help me,\,thanks in advancee
I need to redirect this page in the .htaccess file (I changed the location from a folder called boutique to the root directory)
http://www.bonniegreendesigns.com.au/boutique/index.php?main_page=page&id=20
TO
http://www.bonniegreendesigns.com.au/index.php?main_page=page&id=20
This is the code I wrote, but its not working – any ideas what is wrong? Thanks Jodi
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{QUERY_STRING} ^id=20$
RewriteRule ^/index.php$ http://www.bonniegreendesigns.com.au/index.php?main_page=page&id=20 [L,R=301]
Well, helped a lot to fix my httpdconf…
that’s a wonderfull collection thanks for share…
I must say…
keep it up buddy!
Eric
Hi,
I cant find a way to redirect a folder and not a page or file.
The folder is /url/rotator/ but it doesnt exist anymore and there’s normally a random query string of names after /rotator/
Like this http://www.mysite.com/url/roator/Myname_MyRotatorName
I want anything after http://www.mysite.com/url/rotator/ to go somewhere else, can someone write this for me?
Thank you for that tutorial!
@ Jodi
Probably too late (It’s been 4 months since you posted) but I think the problem with your code is your carrot (^) at the beginning of your regex string for the RewriteCond statement.
Here’s your code:
RewriteCond %{QUERY_STRING} ^id=20$
RewriteRule ^/index.php$ http://www.bonniegreendesigns.com.au/index.php?main_page=page&id=20 [L,R=301]
Here’s what it should be:
RewriteCond %{QUERY_STRING} id=20$
RewriteRule ^/index.php$ http://www.bonniegreendesigns.com.au/index.php?main_page=page&id=20 [L,R=301]
The only difference being the removal of the “^” in front of “^id=20$” on the “RewriteCond” line.
The %{QUERY_STRING} variable in this case actually would contain “main_page=page&id=20″ because it contains everything that comes after the “?” character. So with the regex string of “^id=20$” you are saying:
“Match this string if the string begins with “id” and ends with “20″”.
The string does not begin with id, it begins with “main_page”, therefore the match fails and the rewrite rule is skipped.
To Simone Carletti: THANK YOU, THANK YOU, THANK YOU!!!
Great post and exactly what I was needing. Really can’t thank you enough.
The following rewrite is not working:
Trying to go from:
http://www.example.com/here/page.jspa?theID=35
To:
http://www.example.com/anotherpage/9999 (no correlation with theID above)
Using:
RewriteRule ^here/page\.jspa\?theID=35$ anotherpage/9999 [R=301,L]
I believe because there is a querystring in the From I cannot use that syntax and must first convert like:
RewriteCond %{QUERY_STRING} ^theID=1$
RewriteRule ^here/page\.jspa$ anotherpage/9999 [R=301,L]
Also, what is the best method if I have over 50,000 redirects from old pages that do not have matching IDs? The theID in the old system does not map to an ID in the new system. Do I have to have 50,000 RewriteCond and 50,000 corresponding RewriteRule?
Thanks for any help on this issue,
Frank
I am new and made stupid permalink changes, about 5 times, on my wordpress blog Lifejustiz® Needless to say google has me over 4100 not found and unreachable errors.
my current permalink structure is: /%post_id%/%postname%/ I am using this for the last 3 months.
I have about five permalinks that I used before the latest that have all the errors:
/%postname% , /%postname%/.html , /%postname%.html , could you possibly show me a modrewrite example of how to design redirect permanent to my new and current permalink /%post_id%/%postname%/
all of my changes to permalink structure have a common post id number or postname..I really do not understand the process of query strings and how they apply. I have spend a thousand hours of readind and research and still cannot understand. I am 73 years old and hate to admit that I have problems understanding this stuff. Please help me get this settle…I will never change a permalink again once I get this fixed.
I am about to lose my mind over this stuff…John Gruhler
Thank you! Your explanation is the missing link to this mod rewrite mystery. Really, this is great.
Best, concise mod_rewrite tutorial out here. Awesome as a refresher on tricky stuff.
I was getting stuck, thanks to you I’ve found the missing link to what I needed to accomplish.
I owe you a beer! ;-)
May be a silly question but when you redirect
http://www.pets.com/show_a_product.php?product_id=7
To
http://www.pets.com/products/7/
The form in show_a_product.php is expecting a product_id
Also there is no page on the server called
products/7/
What am I missing?
Thanks
http://www.xyz.com/c73-Graphic-Desgin?resultpage=2&aid=1
in this URL
“73″ and “2″ and “1″ are Values
i tried to rewrite it like this
RewriteRule ^c([0-9]+)-(.+)-(.+)?resultpage=(.+)&aid=(.+)$ templates.php?cid=$1&resultpage=$4&aid=$5&search=yes.
But its not working… please help me to solve this issue… thanks in advance…!
Hi!
I have a Parameter without a Value, in my URL like that: /home.weblog.html?rss
Now, i want to redirect to a new location /feed/
I try the following, but it doesn’t work:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^rss$
RewriteRule ^home\.weblog\.html$ /feed/? [R=301,L]
It only works, if i put a value to the parameter – for example rss=0 and do the redirect like that:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^rss=0$
RewriteRule ^home\.weblog\.html$ /feed/? [R=301,L]
It seems, that a parameter-name without value is not in the %{QUERY_STRING}…
How can i solve my problem?
I am trying to give each MOVIE there own url name, for example, http://www.helloworld.com/BATMAN. I have been using mod_rewrite to create such url. I have been using following htaccess code to achieve such result.
RewriteEngine ON
RewriteCond %(REQUEST_FILENAME) !-d
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-l
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
The mod_rewrite works perfectly. When A user enters randam movie name (name that does not exist in database), for example, http://www.helloworld.com/abcd, I have created a url redirect which is http://www.helloworld.com/oopsmovienotfound.php. This works fine too. But the problem I am having is this: When user click http://www.helloworld.com/login.php .The url keeps looping between login.php and oopsmovienotfound.php OR the url is forwarded to http://www.helloworld.com/oopsmovienotfound.php beacause database doesnot have “login.php” as a movie name. I thought this command
RewriteCond %(REQUEST_FILENAME) !-f
should have take care of this but its not. Please help. Thank you in advance.
Thanks for this very informative and helpful post!
Best regards, Dirk
You saved me a bunch of time! Nice work! Did not know about the QSA flag.
I have a very long URL. More thant 10 query strings:
http://www.domain.com/test.php?aq=arg1&sw=arg2&de=arg3&fr=>=&hy=&ju=&ki=&lo=&cp=&za=&xs=&cd=&vf=
I want to redirect this page to:
http://www.domain.com/makemyday/art1/arg2/arg3 …
Following .htaccess works only till the 9th parameter.
RewriteCond %{QUERY_STRING} ^aq=([^&]*)&sw=([^&]*) … repeating the same here … [NC]
RewriteRule ^test\.php$ /makemyday/%1/%2/%3/%4/%5/%6/%7/%8/%9/%10/%11/%12/%13/%14? [R=301,L]
RewriteRule ^makemyday/(.*)/ … repeating the same here … (.*)/?$ test.php?search=do&aq=$1&sw=$2 … repeating the same here … [L,NC]
I get the following result:
http://www.domain.com/makemyday/arg1/arg2/arg3////////1/2/3/4
/username couldn’t be more difficult to find
Hey Simone, nice post! I have a problem tough using URL rewrite, I wonder if you could check it out, cause I really can’t figure out why is it not working.
That’s my RewriteRule, in .htaccess:
RewriteEngine On
RewriteRule ^([A-Za-z-]+)/([A-Za-z-\.]+)/?$ loadphoto.php?p=$1&f=$2 [NC,L]
I’m on a local Apache2 web server and that’s the script loadphoto.php:
$s = preg_replace(‘/[\-]+/’, ‘/’, $_REQUEST['p']);
$f = $_REQUEST['f'];
echo “”;
When I load the page through the browser I use this URL:
>localhost/MyWebSite/photos-main/myphoto.jpg
Now, loadphoto.php gets the right data, as a matter of fact the the html img tag is built correctly (at least that’s what I see if I check the html in the browser) but no photo is displayed.
I’ve also tried using the RewriteBase directive with no luck…
What I want is just to display that photo… any suggestion?
Thanks a lot!
Tiz
Hi,
I want to redirect like this:
/silversoft=https://myaccess.corp.com/account?ID=silversoft
i tried using the rewrite url as:
RewriteRule ^/silversoft https://myaccess.corp.com/account?ID=silversoft
but not working. Any thoughts?
Hi,
I am trying to redirect from
http://mysite.com/bob/bob/01-23(variable qsa) to https://example.com/bob/bob.php?id=01-23 and i am not sure how to write the query for this. Please let me know.
Thanks,
Hi,
i want to redirect all my html page in this manner
like contact-us to contact-us.html
i have 250html page, any one give me redirect rule that ,any url comes and it map similar .html page
thank in advance
@Robert
Only 9 parameters are accessible, see apache doc:
“RewriteCond backreferences: These are backreferences of the form %N (1 <= N <= 9), which provide access to the grouped parts (again, in parentheses) of the pattern, from the last matched RewriteCond in the current set of conditions."
I’m sorry if this has been covered: I want to redirect queries that don’t have a numerical order to them. For example, I want to redirect
http://www.goldsmithinsurance.com.mywebsitemockup.com/blog/?Tag=annuity+news
to
http://www.goldsmithinsurance.com.mywebsitemockup.com/tag/annuity-news/
In case it helps, I host on Rackspace Cloud Sites and this is their documentation for their .htaccess environment: http://www.rackspace.com/knowledge_center/article/htaccess-tips-and-tricks-for-cloud-sites
Your help is much appreciated.
- Danny Nelson
THANK YOU! Honestly.
I spent a whole day trying to make virtual subdomains work with queries. QSA was the holy grail that no one talks about.
One simple line.
RewriteRule ^([\w-]*).mysite(/)?$ mysite/decoder/?member=$1 [QSA,L]
Next step- retain subdirectories from original URL.
Hi
Search results showing mixed contents.Search terms are double byte characteres special characters. I have written below code in apache httpd conf file but still showing up mixed contents instead showing only what was intended.
RewriteRule ^/(.._..[^/]?)/search/(.+) /$1/search.cfm/$2 [R=301,B,NE,L]
Please help me
Thanks
Sankar