Mod Rewrite: Handling two Get Variables
How can I edit this url rewrite to include a further get variable being appended to the URL? I have tried a few attemps but I开发者_开发百科 always get a 500 internal server error!
I have added comments to show what I am trying to achieve.
# /view.php?user=h5k6&page=1 externally to /h5k6/1
# Some times the page get variable will not exist so it should just show /h5k6
RewriteCond %{THE_REQUEST} ^GET\ /view\.php
RewriteCond %{QUERY_STRING} ^([^&]*&)*user=([^&]+)&?.*$
RewriteRule ^view\.php$ /%2? [L,R=301]
# /h5k6/1 internally to /view.php?t=h5k6&page=1
RewriteRule ^([0-9a-z]+)$ view.php?t=$1 [L]
Thanks all for any help
The problem with URI query arguments is that they may appear in any order. With two arguments you just have two permutations (A before B and B before A). But the more arguments you want to extract the more permutations you have (n!).
That means you should put the arguments in the right order so that you can them at a time:
RewriteCond %{THE_REQUEST} ^GET\ /view\.php
RewriteCond %{QUERY_STRING} ^(([^&]*&)*)(page=[^&]+)&?([^&].*)?$
RewriteCond %3&%1%4 ^(([^&]*&)*)(user=[^&]+)&?([^&].*)?$
RewriteCond %3&%1%4 ^user=([^&]+)&page=([^&]+)&?([^&].*)?$
RewriteRule ^view\.php$ /%1/%2?%3 [L,R=301]
The first condition checks the request line like in your rule. The second condition picks the page argument and puts it at the start of the query string. The third condition does the same with the user argument so that the order always is: first user, second page. Then we use the fourth condition to take both argument values at a time to use them in the RewriteRule
replacement. The rest of the query is appended to the replacement URI (see %3
) but you can leave that off if you want.
As you see, the more arguments you want to extract, the more complex it gets. And it is easier to do that with a language that is more powerful than mod_rewrite like PHP.
精彩评论