301 Redirecting URLs based on GET variables in .htaccess

后端 未结 3 1481
南方客
南方客 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]
    
    0 讨论(0)
  • 2020-12-04 01:01
    RewriteCond %{QUERY_STRING} option=com_content&task=view&id=70&Itemid=82
    RewriteRule ^index.php http://www.example.com/business/banks/? [R=301,L]
    

    The ? will prevent the url the user is sent to from having the same query string as the origin page.

    0 讨论(0)
  • 2020-12-04 01:02

    In summary, you could use RedirectMatch with a regex that will match the full URL, including query string. That will let you rearrange parts of the URL, but if you have to do conversions like "opendocument&part=1" to "welcome" (where the new URL is completely different from the original one), you might need a RewriteMap - or perhaps better, just send all URLs to page.php and parse the query string in PHP.

    EDIT: If it's just a few URLs you want to redirect, you could probably write out individual rules like

    RedirectPermanent http://www.example.com/bunch.of/unneeded/crap?opendocument&part=1 http://www.example.com/page.php/welcome
    RedirectPermanent http://www.example.com/bunch.of/unneeded/crap?opendocument&part=2 http://www.example.com/page.php/prices
    
    0 讨论(0)
提交回复
热议问题