301 Redirecting URLs based on GET variables in .htaccess

人走茶凉 提交于 2019-11-28 01:31:41

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]

@Jack Ross

RewriteCond %{QUERY_STRING} option=com_content&task=view&id=70&Itemid=82
RewriteRule ^index.php http://www.domain.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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!