Friday, March 9, 2018

apache mod_rewrite


  • The caret, ^, signifies the start of an URL, under the current directory. This directory is whatever directory the .htaccess file is in. You’ll start almost all matches with a caret.




  • The dollar sign, $, signifies the end of the string to be matched. You should add this in to stop your rules matching the first part of longer URLs.
  • Query string is read until "?"


  • example

    RewriteCond %{QUERY_STRING} ^resid=ID
    RewriteRule ^/eid?  http://store.datascrip.com/? [R=301,L]


    Force SSL
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

    Redirrect everything to new URL
    RewriteRule /.* http://www.new-domain.com/ [R]

    redirrect certain query string match + sub path to new URL
    RewriteCond %{QUERY_STRING} ^resid=ID$
    RewriteRule ^/eid? http://new.com/ [R,L]

    this will redirrect testing.com/eid?resid=ID to http://new.com
    the symbol $ is to indicate the string end


     RewriteCond %{HTTP_HOST} ^gab.com
     RewriteRule "^(.*)/p/7074689$" "https://gab.com/p/7075394" [R=301,L]

    this will rewrite request go to gab.com/* and end with that redirrect to different place

    Block all access to /test/* except /test/gab/*

    RewriteCond %{HTTP_HOST} ^abc.com
    RewriteCond %{REQUEST_URI} ^/test
    RewriteRule  "!^/test/gab(.*)" "-" [F]

    # rewrite rule base on akamai country code for maintenance pages
     RewriteCond %{HTTP:X-Akamai-Edgescape} code=MY
     RewriteCond %{REQUEST_URI} !^/maintenance
     RewriteRule ^(.*)$ /maintenance/ES/maintenance.html [R=301,L]

    https://www.cheatography.com/davechild/cheat-sheets/mod-rewrite/