8

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?

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

1 Answer 1

8

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.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.