使用htaccess从一个路径重定向到另一个路径


Redirect from one path to another using htaccess

使用htaccess从一个路径重定向到另一个路径

我有一些像这样的url:-

https://www.example.com/au/path1
https://www.example.com/sg/path1
https://www.example.com/ca/path1 

和更多,我想重定向这些url到这种类型:-

https://www.example.com/au/path2
https://www.example.com/sg/path2
https://www.example.com/ca/path2

但我没有得到想要的结果,这是我的代码:-

RewriteEngine On 
RewriteCond %{REQUEST_URI} path1
RewriteRule ^(.*)$ %{REQUEST_URI}/path2 [R=301,L]

另一种方法是将这些url逐个重定向到Apache mod_alias的redirect指令。

在你的根目录/中试试这个。Htaccess文件:

RedirectPermanent /au/path1 /au/path2
RedirectPermanent /sg/path1 /sg/path2
RedirectPermanent /ca/path1 /ca/path2

您可以将RedirectPermanent更改为RedirectTemp用于临时重定向。

您需要捕获请求uri的前缀并使用它来进行重定向。像这样:

RewriteRule ^(.*)/path1$ $1/path2 [R=301,L]

更新:

如果您需要重定向一组不断变化的别名,则可能需要查看RewriteMap。此模块允许您使用不同的外部源来为重写提供映射。

例如,您可以有一个包含键、值对的文本文件:

foo/bar /foo-new/bar
bar/foo /bar/foo-new

然后结合这个map重写规则:

RewriteMap examplemap "txt:/path/to/file/map.txt"
RewriteRule "^(.*)$" "${examplemap:$1}"

然后,您可以确保在需要更改映射时更新该文件(如果来自Drupal)。Apache将查看文件的修改时间,如果发生更改,则刷新缓存。

您也可以使用外部应用程序或使用其他一些改进的资源。