TechTips Vol II – Linux HowTo Apache Rewrite

  1. Have you ever needed a page to auto redirect to another page i.e.
    • http://www.russgreenwald.com to
    • https://www.russgreenwald.com/newsite/
  2. Have you ever needed a page to display a more favorable address for content, but the original address can’t be changed? i.e.
    • http://www.russgreenwald.com/867/developer-site/test/210 to
    • http://www.russgreenwald.com/devsite/210
  3. In my example below, a client needed addresses auto generated from a software package to redirect to a slightly different address. i.e. the software package would generate
    • http://www.domain.com/project/query/112.
      That address would not work, so apache rewrite allowed me to auto redirect that to
    • http://www.domain.com/project/112

First and foremost all my information came from this awesome Apache Rewrite Guide Steps:

  1. I set my apache rewrite rules in a .htaccess file. Note: If you want to do a simple http to https redirect I do the below in an apache conf file, in the virtual host port 80 directive.
    • RedirectPermanent / https://www.domainname.com/site
  2. Make sure apache is configured to allow .htaccess files. “AllowOverride ALL”
  3. Using example 3 above, I put the below in my .htaccess file, located in the DocumentRoot of my site.

    • RewriteEngine on
    • RewriteRule ^(.*)/project/query/([0-9]+) /$1/project/$2 [R]
  4. What does it mean?

    • The ^ defines the root of the site i.e. http://www.domain.com/ so anything after the ^ is after www.domain.com
    • Anything within () is a pattern that can be called in the new domain using $1 for the first pattern seen, then $2 for the second, etc..
    • Patterns
      1. (.) means anything really. The period allows any character and the star () means “0 or N of the preceding text (N > 0)”
      2. [0-9]+ defines any number 0-9 repeated. So 1 or 11 or 111 or 111 or 2 or 22 or 2231, etc.
      3. $1 repeats the expression that is called right after the www.domain.com/ trailing slash. So using the example www.domain.com/project/ $1 is project.
      4. $2 repeats the expression right after query, so in the example http://www.domain.com/project/query/112 that is the “112”.

Comments are closed.