Apache rewrite (mod_rewrite)

Discard query string in rewrite rule

eg. we want rewrite
http://www.foo.com?query=abc to http://www.foo.com/noquery Apache always appends the original query string (?query=abc) to the target URL which we don’t want.

  • In Apache 2.4 or later you can use the QSD option (qsdiscard) to remove the query string like:
RewriteCond %{QUERY_STRING} ^query=abc$  
RewriteRule ^/$ /noqueries [QSD,R=301,L]  
  • Apache 2.2 and early don't support QSD option, need a trick, add ? at the end of target url (empty query string), like:
RewriteCond %{QUERY_STRING} ^query=abc$  
RewriteRule ^/$ /noqueries? [R=301,L]  

reference doc: https://www.philipphoffmann.de/blog/2012/08/16/how-to-discard-the-query-string-in-a-rewriterule-apache-mod_rewrite/

Don't encode query string when rewrite

  • mode_rewrite default re-urlencode the query string param, this cause the param encode twice, add NE (no escape) option to avoid this.
RewriteRule ^/lookup$  /search/companies   [R=301,NC,NE,L]  

reference doc: http://stackoverflow.com/questions/6520484/mod-rewrite-urlencoding-an-already-urlencoded-querystring-parameter-any-way-to

Query string condition rewrite

  • use query parameter decide which url to rwrite. eg:
RewriteCond %{QUERY_STRING} ^ntype=1&ncid=2$ [NC]  
RewriteRule ^/categoryTop\.php$ /news/business? [NC,L,R=301]

RewriteCond %{QUERY_STRING} ^ntype=1&ncid=3$ [NC]  
RewriteRule ^/categoryTop\.php$ /news/world? [NC,L,R=301]  

Rewrite Option

  • NC - no case (ignore canse)
  • L - last rewrite rule
  • R - force redirect, default R=302, you can specify other value, like: 301
  • F - force url to be forbidden. return 403 HTTP
  • G - force url to be gone. return 410 HTTP
  • P - force proxy
  • N - next round
  • C - chained with next rule
  • T - T=MINIE-type, fore mime type
  • NS - used only if no internal sub-request
  • QSA - query string append
  • QSD - query string discard, available on apache 2.4 or later.
  • NE - no escape, use this avoid encode query string twice.
  • PT - pass through to next hander
  • S - skip next rules S=num
  • E - set env variable E=var:val

Some rewrite example

  • rewrite from

Offical doc