301 Redirecting URLs based on GET variables in .htaccess

后端 未结 3 1497
南方客
南方客 2020-12-04 00:28

I have a few messy old URLs like...

http://www.example.com/bunch.of/unneeded/crap?opendocument&part=1

http://www.example.com/bunch.of/unneeded/crap?opend

3条回答
  •  庸人自扰
    2020-12-04 00:59

    As the parameters in the URL query may have an arbitrary order, you need to use a either one RewriteCond directive for every parameter to check or for every possible permutiation.

    Here’s an example with a RewriteCond directive for each parameter:

    RewriteCond %{QUERY_STRING} ^([^&]&)*opendocument(&|$)
    RewriteCond %{QUERY_STRING} ^([^&]&)*part=1(&|$)
    RewriteRule ^bunch\.of/unneeded/crap$ /page.php/welcome? [L,R=301]
    
    RewriteCond %{QUERY_STRING} ^([^&]&)*opendocument(&|$)
    RewriteCond %{QUERY_STRING} ^([^&]&)*part=2(&|$)
    RewriteRule ^bunch\.of/unneeded/crap$ /page.php/prices? [L,R=301]
    

    But as you can see, this may get a mess.

    So a better approach might be to use a RewriteMap. The easiest would be a plain text file with key and value pairs:

    1 welcome
    2 prices
    

    To define your map, write the following directive in your server or virual host configuration (this directive is not allowed in per-directory context):

    RewriteMap examplemap txt:/path/to/file/map.txt
    

    Then you would just need one rule:

    RewriteCond %{QUERY_STRING} ^([^&]&)*opendocument(&|$)
    RewriteCond %{QUERY_STRING} ^([^&]&)*part=([0-9]+)(&|$)
    RewriteRule ^bunch\.of/unneeded/crap$ /page.php/%{examplemap:%2}? [L,R=301]
    

提交回复
热议问题