Reputation: 23
I am currently working on a php website and I am pretty unexperienced with htaccess rewrite rules and conditions. My question would be how could I get only the first directory from a link?
So for example I have a link "example.com/page1/page2/?something=something" and I need the output to be page1 so I can redirect it to index.php?p=page1
And also what would I do to get the output of "page2" or "?something=something"? So in this case I would redirect it to index.php?p=page1&ap=page2&something=something
I know that I could theoretically use:
RewriteRule ^page1/page2$ index.php?p=page1&ap=page2
But in this case I can't predict what page1 and page2 will be, so assume it's like a variable:
RewriteRule ^{somevariable}/{someothervariable}$ index.php?p={somevariable}&ap={someothervariable}
And in this case the output would be "index.php?p=page1&ap=page2".
I tried to search for this on web but I didn't really know what exactly to search for.
Thanks in advance!
Upvotes: 1
Views: 119
Reputation: 6148
You can indeed use RewriteRule
to parse the URL...
RewriteRule ^(.*?)/(.*)/?$ /index.php?p=$1&ap=$2 [L,QSA]
^ : Match the start of the string
(.+?) : Match any character one or more times; non-greedy
/ : Match a slash
(.+) : Match any character one or more times
/? : Optionally match a slash
$ : Match the end of the string
L : Stops processing rules
QSA : Append the original query string
Example
http://www.somewebsite.com/page1/page2?id=1435
print_r($_GET);
/*
Array
(
[p] => page1
[ap] => page2
[id] => 1435
)
*/
Upvotes: 1