使用 GET 变量的 .htaccess 通配符重定向

.htaccess Wildcard Redirect With GET Variables

我正在尝试将我网站上的所有以下 URL 重定向到新版本。这是目标:

之前(注意没有'.php')

https://example.com/view?username=asdf1234

重定向至(使用“.php”并在 'tool' 文件夹内)

https://example.com/tool/view.php?username=asdf1234

我已经尝试了几个示例,但无法弄清楚。这是我最好的猜测

RewriteEngine On
RewriteRule ^/view\?username=(.+) /tool/view.php?%1 [L,R=301]

添加

RewriteEngine On
RedirectMatch ^/view(.*)$ https://example.com/tool/view.php

重定向成功,但是是302重定向。当我添加 [L,R=301] 时出现 500 错误。

您可以尝试否定断言:

RewriteEngine On
RewriteCond "%{REQUEST_URI}" ^/tool/?.*$
RewriteRule ".?" "-" [S=1]
RewriteRule "^/(.*)$" "/tool/?%{QUERY_STRING}" [L,R=301]
  • 第一条规则说明 URL 以 /tool 开头的条件。
  • 第二个规则声明如果第一个规则通过,跳过下一个 规则。
  • 第三条规则说实现重定向到 /tool/(TheUrlYouVisited.whatever)

因此,如果 URL 不是以 /tool 开头,则不会跳过第三条规则,因此您可以捕获所有重定向。


作为测试,您也可以添加一个简单的:

RedirectMatch ^/view(.*)$ http://www.example.com/tool/view

如果这不起作用,您就知道还有其他事情正在发生。