Convert path info into query string arguments via .htaccess

  • WritingBadCode
  • Graduate
  • Graduate
  • User avatar
  • Posts: 214
  • Loc: Sweden

Post 3+ Months Ago

I have not needed .htaccess before and I guess stuff is doable without it. But now I really need it.

I wrote the following:
Code: [ Select ]
RewriteEngine on
Options +FollowSymlinks
RewriteRule ^test/templates/ http://site/templates.php
  1. RewriteEngine on
  2. Options +FollowSymlinks
  3. RewriteRule ^test/templates/ http://site/templates.php


This partially does what I want, witch is when a user visits site/test/templates/ the file templates.php is loaded (from the right folder too!).

But I want this:

site/test/templates/argument/argument2/argument3/

and when a user does this I want templates.php to be loaded like this: templates.php?a1=argument&a2=argument2&a3=argument3 so I can extract values and also I want argument2 and argument3 to be optional.

I'm asking for a lot I guess, any help? :)
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9087
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

You will want to do something like this:

Code: [ Select ]
RewriteRule ^test/templates/([a-zA-Z0-9_-]+/)([a-zA-Z0-9_-]+/)?([a-zA-Z0-9_-]+/)?$ http://site/templates.php?a1=$1&a2=$2&a3=$3 [QSA,L]


The QSA part stands for Query String Append and allows you to modify the query string. By default the query string is passed through unchanged, so by adding that part you can re-inject values into the query string as shown above. The L part means its the last rule and rule rewriting should stop there, you probably most likely want that.

In the three sets of parenthesis you will notice the last two have a question mark after it which makes each set there optional. The sets of parenthesis also translate into the $1, $2, and $3 variables.

Let me know if that works for you :)
  • WritingBadCode
  • Graduate
  • Graduate
  • User avatar
  • Posts: 214
  • Loc: Sweden

Post 3+ Months Ago

Thank you bigweb! This solved my issue almost exactly as I wanted.

The thing I noted however was that the '/' (backslash?) char also was parsed to the string at the end. This is not really a big issue and I'm sure I can figure it out myself soon enought after some regex studying. :P

I had a lot to do today so the answer has taken some time. However I appreciate the code you provided.

This will be extremely useful. :D

Post Information

  • Total Posts in this topic: 3 posts
  • Users browsing this forum: No registered users and 90 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.