Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

I'd like to use mod_rewrite within the .htaccess file to rewrite folders to a var string. Below is examples of current and what I would prefer.

  • Current URL: example.com/main/folder1/folder2/folder3
  • Preferred URL: example.com/parser.php?var1=folder1&var2=folder2&var3=folder3

How can I rewrite the current URL's to preferred URLs?

share|improve this question
1  
Are there always exactly three levels of folder? If there are always exactly three it isn't a hard problem. If there a are "up to three" it is trickier, but still doable (you might need a separate rule for when there is one, then another when there are two, etc). If there are an arbitrary number, I don't believe that mod_rewrite can do it. –  Stephen Ostermiller Jul 8 at 11:59
    
Just to note, as per the original question (before the edit), a "301 redirect" is probably not what you want. You probably mean an "internal rewrite". ie. the URL example.com/main/folder1/folder2/folder3 should remain in the address bar - is that correct? –  w3d Jul 8 at 12:33
    
Yes internal rewrite not 301. the first level [link]example.com/main/folder1 will have link to the folder2 and the folder2 link to folder 3 –  exarhis Jul 8 at 14:01

1 Answer 1

up vote 2 down vote accepted

You can use these three rewrite rules which handle up to 3 levels of directories:

RewriteEngine on
RewriteRule ^main\/([^\/]+)\/([^\/]+)\/([^\/]+)\/? /parser.php?var1=$1&var2=$2&var3=$3 [L]
RewriteRule ^main\/([^\/]+)\/([^\/]+)\/?  /parser.php?var1=$1&var2=$2 [L]
RewriteRule ^main\/([^\/]+)\/?  /parser.php?var1=$1 [L]

In those regular expressions:

  • ^main\/: starts with "main/"
  • ([^\/]+): a bunch of characters that are not slashes (in a capturing group to be pulled out with $1, $2, or $3)
  • \/? an optional ending slash
  • [L] the last rewrite rule (so that later rewrite rules don't also get triggered)

I usually prefer to pass all the folders as a single variable like so:

RewriteEngine on
RewriteRule ^main\/(.*) /parser.php?folders=$1

then your PHP parser could split the folders on the slash to get the three variables you want.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.