Rewrite up to three folders into three query string parameters to a PHP script

Rewrite up to three folders into three query string parameters to a PHP script - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, apache, mod-rewrite, custom-variables, .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


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?


Solution :

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.


Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect