Skip to main content

Rewrite / Redirect URI - Apache

Ref: Apache mod_rewrite Introduction

Ref: Apache Module mod_rewrite

Use PCRE to rewrite URL

  • !: not match
  • =: match plain string
# RewriteEngine { on | off }
RewriteEngine on

# RewriteCond "<test string>" "[!]<RegExp condition>" [<flags>]
RewriteCond "%{REQUEST_URI}" "^/api/"

# RewriteCond "<test string>" "[!][<|>][=]<string condition>" [<flags>]
RewriteCond "%{REQUEST_URI}" "=/data.json" [NC]

RewriteRule "<RegExp pattern>" "<substitution>" [<flags>]
  • By default, the query string is passed through unchanged
  • To replace query string, append ?<query> to <substitution>
  • To combin original query string, use [QSA] flag

RewriteCond

Ref: RewriteCond Directive

  • RewriteCond only apply to the next one RewriteRule
  • Multiple RewriteCond implicit AND
  • Flag [OR] can be append to RewriteCond

Flags:

  • [NC]: no case, case insensitive
  • [QSA]: query string append
  • [OR]: combine RewriteCond with OR logic
  • Flags is comma-separated [NC,QSA]

Variables:

VariableDescriptionValue
REMOTE_ADDRclient IP address
HTTPShttpson or off
REQUEST_SCHEMEschemehttp or https
REQUEST_FILENAMEfull path of the requested file/var/www/data.html
REQUEST_URIrequest URI, excludes the query string/data.html
THE_REQUESTHTTP request lineGET /data.html HTTP/1.1

Redirect HTTP to HTTPS

RewriteEngine on
RewriteCond "%{HTTPS}" "=off"
RewriteRule "^/?(.*)" "https://%{HTTP_HOST}/$1" [R,L]

See also: HSTS

Debug

LogLevel alert rewrite:trace3