问题原文
原帖链接 · Miama · CC BY-SA 4.0
I'm trying to redirect a URL ending with parameters to another URL without those parameters.
https://example.com/newsroom/news-events/news.html?L=1&tx_news_pi1%5Bnews%5D=29&tx_news_pi1%5Bcontroller%5D=News&tx_news_pi1%5Baction%5D=detail&cHash=1a27801759cdd648cfd823643ab0e2e1
to
https://example.com/en/news/news/
How can I do that?
社区高分解答
原帖链接 · MrWhite · CC BY-SA 4.0
To redirect the exact URL as stated you will need to use mod_rewrite (ie. RewriteRule and RewriteCond directives) since only mod_rewrite is able to match the query string part of the URL (ie. everything after the first ?).
Try the following near the top of the .htaccess file.
RewriteEngine On
RewriteCond %{QUERY_STRING} =L=1&tx_news_pi1%5Bnews%5D=29&tx_news_pi1%5Bcontroller%5D=News&tx_news_pi1%5Baction%5D=detail&cHash=1a27801759cdd648cfd823643ab0e2e1
RewriteRule ^newsroom/news-events/news\.html$ /en/news/news/ [QSD,R=302,L]
The QSD flag (Query String Discard) on the RewriteRule directive is necessary in order to discard the original query string from the redirected response. Otherwise, the original query string is passed through as-is and you would end up with /en/news/news/?L=1&tx_news_pi1%5Bnews.....
The preceding RewriteCond (condition) directive matches the entire query string exactly as stated. The = prefix on the CondPattern (2nd argument) makes this an exact string match, as opposed to a regex match.
To match any query string, including an entirely empty query string, then simply remove the RewriteCond directive.
R=302 - Note that this is a 302 (temporary) redirect. If this is intended to be permanent then change this to 301 - but only once you have confirmed this is working as intended since 301s are cached persistently by the browser which can result in potential caching problems.
Note also that if you have existing directives in .htaccess then the order of these directives can be important.
Reference:
a url with ending parameter to url without that parameter
Strictly speaking, the "ending(sic) parameter" would be interpreted as just cHash=1a27801759cdd648cfd823643ab0e2e1 in the example URL stated, ie. the last URL parameter. All the URL parameters together, make the "query string", which I believe is what you are referring to.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
