Thursday, July 18, 2013

Apache Rewrites to hide variables

I've been absolutely fighting with rewrites over the past week. Why do you want to know about rewrites? You can easily hide variables with it.

Example

 Let's say you want to hide a variable in a clean url. I want http://www.store.com/catfood.html instead of http://www.store.com/product.html?p=1234233

If you are dealing with apache servers then you'll be dealing with the .htaccess file. Here are the steps required to make that example happen.
Step 1: open .htaccesss. If you are on a linux server running Apache you should have one. If it isn't showing then it might be a hidden file. If you don't have an .htaccess file then you need to make one. It should be in the root of your public_html folder on your server.
Step 2: RewriteEngine On   #you need this bit of code to turn on Rewrites
Step 3: RewriteRule PATTERN SUBSTITUTION FLAG and example would look like this RewriteRule ^(.*)?\.html product.php?p=%1$1 [QSA] 

The Pattern is "^(.*)?\.html" which uses a regular expression to say Any characters before .html. So if someone types in toyota-camry.html it will take "toyota-camry" from the url - what it does with it is explained in the next part

The Substitution says "okay you have toyota-camry as a variable - we'll place that variable in your substitution and on the server we'll run product.php?p=toyota-camry. That means you with this rewrite we can obstruct the variable from view and the end user will just see the clean url. Pretty cool.
So this little .htaccess rewrite handles hiding the variable and give your site a clean looking URL. What this doesn't do is actually process the variable. If you are using PHP you'd need some $_GET methods to process the product id that is being passed to it. That is another lesson all together.

The Flag is [QSA].  There are lots of different flags, but what that flag means is "append query string from request to substituted URL".  This way you can add on additional query items to the newly formed URL.  Basically it means you could have catfood.html?t=wet and it would pass the varible properly without ignoring the variable.

Some other cool things you can do with rewrites:

  • You are trying to create dynamic subdomains. Otherwise you'd have to setup each instance in the DNS record. (This one requires adding a wildcard A record on the DNS record)
    •  RewriteEngine on
      RewriteCond %{HTTP_HOST} ^(.*)\.exampleDomain\.com
      RewriteRule ^(.*)$ http://exampleDomain.com/%1/$1 [L]
  • You want to hide directories and file structure. http://www.domain.com/gallery.html instead of http://www.domain.com/pictures/gallery1/index.php
    •  RewriteEngine on
      RewriteRule gallery.html$ pictures/gallery1/index.php [L]

Additional resources:

This is an absolutely fantastic resource by addedbytes Url rewriting for Beginners

No comments: