大网数据广告活动
网站运营与故障问答

How to redirect a URL and remove parameters using .htaccess?

· 52CE 我爱测

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…

问题原文

原帖链接 · 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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2021-08-11)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。