Mobile app version of vmapp.org
Login or Join
Nimeshi995

: Rewrite up to three folders into three query string parameters to a PHP script I'd like to use mod_rewrite within the .htaccess file to rewrite folders to a var string. Below is examples of

@Nimeshi995

Posted in: #Apache #CustomVariables #Htaccess #ModRewrite

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?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Nimeshi995

1 Comments

Sorted by latest first Latest Oldest Best

 

@Heady270

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

RewriteEngine on
RewriteRule ^main/([^/]+)/([^/]+)/([^/]+)/? /parser.php?var1=&var2=&var3= [L]
RewriteRule ^main/([^/]+)/([^/]+)/? /parser.php?var1=&var2= [L]
RewriteRule ^main/([^/]+)/? /parser.php?var1= [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 , , or )
/? 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=


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

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme