重定向子目录根和根子目录,避免死循环 [英] Redirect subdir to root and root to subdir, avoiding infinite loop

查看:139
本文介绍了重定向子目录根和根子目录,避免死循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我公司目前已经部署了以下的.htaccess在我的htdocs根:

I currently have deployed the following .htaccess in my htdocs root:

RewriteEngine On

# Map / to /foo.
RewriteRule ^$ /foo/ [L]

# Map /x to /foo/x unless there is a x in the web root.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/foo/
RewriteRule ^(.*)$ /foo/$1

此重定向example.com/foo/whatever是否匹配其他目录,而其他应用程序生活(狐狸例如example.com/admin/whatever,应保持这种方式),除了example.com/whatever~~V。行为的一部分是期望的。但现在我有两个网址上的富每一页,我有example.com/foo/whatever和example.com/whatever。我想打301重定向所有请求从/富/ X为/ X,但如果我添加

This redirects example.com/foo/whatever to example.com/whatever, except if it matches other directories where other apps live (fox example example.com/admin/whatever, which should be kept that way). That part of the behaviour is desired. But now I have two urls for every page on foo, I have example.com/foo/whatever and example.com/whatever. I want to make a 301 redirect for all requests from /foo/x to /x, but if I add

# Redirect /foo/x to /x
RewriteRule ^foo/(.*)$ /$1 [R=301,L]

到的.htaccess我明明得到一个重定向无限循环。我怎样才能达到我想要的?在此先感谢任何帮助,您可以提供。

to the .htaccess I obviously get a redirection infinite loop. How can I achieve what I want? Thanks in advance for any help you may provide.

推荐答案

要prevent重定向循环,你可以做几件事情。如果您正在运行了最新的Apache的版本,你有机会获得 [结束] 标志。你可以用它来完全停止重写,当你在内部重写,preventing重定向在踢。

To prevent a redirection loop, you can do a couple of things. If you are running an up-to-date Apache version you have access to the [END] flag. You can use this to stop rewriting completely when you internally rewrite, preventing the redirect to kick in.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/foo/
RewriteRule ^(.*)$ /foo/$1 [END]

# Redirect /foo/x to /x
RewriteRule ^foo/(.*)$ /$1 [R=301,L]

请参阅文档

如果您没有访问该标志,你会得到一个内部服务器错误。在这种情况下,我会建议让重定向规则只匹配在外部请求。

If you don't have access to that flag you'll get an internal server error. In that case I would recommend to let the redirect rule only match on an external request.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/foo/
RewriteRule ^(.*)$ /foo/$1

# Redirect /foo/x to /x
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /foo/(.*)\ HTTP
RewriteRule ^ /%2 [R=301,L]

这篇关于重定向子目录根和根子目录,避免死循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆