Not quite getting how mod_rewrite regex works when flatting urls with multiple variables.
Hello hello,
Ok, so I'm working on another website but I have run into what I'm sure is a pretty basic problem that I can't seem to wrap my head around. I use mod_rewrite pretty frequently to flatten the most basic types of dynamic urls, those with only one variable. But now I need to figure out how to configure my htaccess to handle urls that always have one variable, but sometimes also have 2-3.
Now if I knew the same number of variables would be present all the time I think I could handle it, but when there is a variable number of variables I just can't seem to figure out what I'm doing.
Here is an example of what I do know how to do. Let's say I want to change the url:
http://mywebsite.com/profile/jeremy/
into:
http://mywebsite.com/profile.php?name=jeremy
I'd use:
ReWriteRule ^profile/([A-Za-z]+)/$ /profile.php?name=$1
but if sometimes I also add extra variables like so:
http://mywebsite.com/profile/jeremy/action/sort/order/desc/
into:
http://mywebsite.com/profile.php?name=jeremy&action=sort&order=desc
Then I just can't seem to wrap my head around it. Especially if depending on circumstances I might have urls like so where the 2nd variable in the previous example is missing, but the third is still round:
http://mywebsite.com/profile/jeremy/order/desc/
I've Googled around but it seems most websites toughing on the subject are either too simple (and just give examples with single variables) or are too complicated and assume I already have abase level of regex knowledge which I sadly lack.
So would any kindly Mefite want to give me a walk through on what exactly I should be trying to do (and most importantly why, so that I can avoid just rote copy/pasting and instead be able to solve these kind of problems myself in the future =)
Thanks much!
Jeremy
I'm sure you could do it in one, but this seems much more clear to me. Readability and maintainability is typically more important than (presumed) optimization. If you're doing any more rewriting than one or two vars, consider tossing the entire string into a get var that is processed by a server-side script.
It also looks like you're trying to set both query KEYS and VALUES in your urls -- ie, you want to do something like :
In theory, you can do this, but I think it's going to be super confusing, and I've personally never seen an app work this way -- it forces you to have to handle a crapload of 404s that would otherwise be routed by apache.
Something else to keep in mind: are you limiting user names to just letters? Your rewrite will fail for people using underscores, spaces, or numbers in their names.
posted by fishfucker at 6:10 PM on June 10