htaccess 301 重定向文件夹,但不重定向子文件夹
我需要从
重定向到 http://example.com/newfolder
但保留:
http://example.com/folder/subfolder
其中 这是。这可能吗?我似乎无法在不引起一堆重定向混乱的情况下实现它。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Jestep上面的答案重定向“/root-directory”,但无法重定向“/root-directory/”。这可以通过简单地修复和简化:
这将重定向“/folder”和“/folder/”,但保留所有子目录。
Jestep's answer above redirects "/root-directory" but fails to redirect "/root-directory/". This can be fixed and simplified by simply:
This will redirect "/folder" and "/folder/" but leave all sub-directories alone.
我在这里尝试了其他方法,但效果参差不齐。无论如何,我都不是 Apache 专家,但这里有一个每次都对我有用的简单的单行代码。我只是使用
RedirectMatch
而不是Redirect
并包含一个非常简单的正则表达式来在尾部斜杠处或之前结束匹配,这意味着子目录永远不应该符合匹配条件。RedirectMatch 301 ^/folder[/]?$ /newfolder
I've tried other methods here with mixed success. I am no Apache expert by any means, but here is the simple one-liner that works every time for me. I just use
RedirectMatch
instead ofRedirect
and include a very simple RegEx to end the match at or just before the trailing slash, meaning that subdirectories should never qualify as a match.RedirectMatch 301 ^/folder[/]?$ /newfolder
我刚刚遇到了这个问题,这是我想出的解决方案。我更喜欢这种方法,因为它不会重定向任何子目录。
I just ran into this and here's the solution I came up with. I prefer this method because it doesn't redirect any subdirectory.
也许:
这应该将 /folder 重定向到 /newfolder 但忽略 /folder/subfolder
Maybe:
This should redirect /folder to /newfolder but leave out /folder/subfolder
如果
mod-rewrite
未启用或者您无法在服务器上使用RewriteRule
指令,您可以使用 RedirectMatch 指令="https://httpd.apache.org/docs/2.4/mod/mod_alias.html" rel="nofollow noreferrer">mod-alias 这是apache httpd服务器的默认模块。这会将
/folder/
301 重定向到/newfolder/
。If
mod-rewrite
isn't enabled or you are unable to useRewriteRule
directive on your server, you can useRedirectMatch
directive of mod-alias which is the default module of apache httpd server.This will 301 redirect
/folder/
to/newfolder/
.您使用哪个服务器?
例如,如果您使用 apache 并执行类似的操作,
并将其放入 /folder/ 目录中的 .htaccess 文件中,
则 可以使用 mod_rewrite (假设您可以更改 apache 的设置,这意味着您可以在该虚拟主机中选择 AllowOverride All)更多信息 http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
Which server are you using?
You could for example use mod_rewrite if you use apache and do something like this
and put that in a .htaccess file in your /folder/ directory (assuming you can alter apache's settings, meaning you have the option AllowOverride All in that virtual host)
Here's some more info http://httpd.apache.org/docs/2.0/misc/rewriteguide.html