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?

  • 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. Jul 8, 2014 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?
    – MrWhite
    Jul 8, 2014 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, 2014 at 14:01

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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