TechTips Vol II – Linux HowTo Apache Rewrite

  1. Have you ever needed a page to auto redirect to another page i.e.
    • to
  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.
    • to
  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
      That address would not work, so apache rewrite allowed me to auto redirect that to

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 /
  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. so anything after the ^ is after
    • 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 trailing slash. So using the example $1 is project.
      4. $2 repeats the expression right after query, so in the example that is the “112”.

Comments are closed.