4

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. – Stephen Ostermiller Jul 8 '14 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 '14 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 '14 at 14:01
5

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.

  • Can we simplify this answer by removing the /main/ directory from the question, using only 1 subdirectory, and accounting for whether or not there is a trailing slash? That is - how to rewrite example.com/foldername and how to rewrite example.com/foldername/ ? (I try removing 'main' from this solution in various ways, but without success) Both of these should go to /index.php?var=foldername – youcantryreachingme Mar 13 '18 at 9:22
  • @youcantryreachingme What you are saying is a completely different situation. You should ask it as a new question. – Stephen Ostermiller Mar 13 '18 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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