Apache将根目录重写到子目录并保留请求的uri

Apache将根目录重写到子目录并保留请求的uri,apache,.htaccess,mod-rewrite,Apache,.htaccess,Mod Rewrite,我想重写一个URL,如https://example.com/abcde至https://example.com/en/abcde和https://example.com/acefr至https://example.com/en/acefr 我试过这样的方法: RewriteRule ^$ /en [R=301] 它可以从https://example.com/至https://example.com/en/;但当我的URL为https://example.com/abcde,保留原始URL

我想重写一个URL,如
https://example.com/abcde
https://example.com/en/abcde
https://example.com/acefr
https://example.com/en/acefr

我试过这样的方法:

RewriteRule ^$ /en [R=301]
它可以从
https://example.com/
https://example.com/en/
;但当我的URL为
https://example.com/abcde
,保留原始URL

我应该在配置文件中写什么

非常感谢

更新1:
我可能没有说明根目录下还有其他子目录,我仍然需要保持访问权限,例如
https://example.com/zh/
https://example.com/hub/

最后,我不想保持URL不变。我也需要换一下。我不介意使用“重定向匹配”规则

为了更好地理解:

https://example.com/abcde  ==> https://example.com/en/abcde
https://example.com/zh/abcde  #KEEP!  (in which subdirectory "zh/" exists)
https://example.com/en/ffsd  #KEEP!  (in which subdirectory "en/" exists)
https://example.com/hub/iyukmyjnrtb  #KEEP! (in which subdirectory "hub/" exists)
非常感谢

更新2: 对不起,有误会。我还需要以下内容的重定向:

https://example.com/abcde/edgs  ==> https://example.com/en/abcde/edgs (in which subdirectory "abcde/" does not exists)

谢谢

您可以在站点根目录中使用此规则。htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 ^$ [OR]
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteRule ^(?!en/)([^/]+/)?.*$ /en/$0 [R=301,L,NC]
测试前,请确保清除浏览器缓存

以下是对该规则每一行的解释:

# if this request is not for an existing file
RewriteCond %{REQUEST_FILENAME} !-f

# if this request is not for an existing directory
RewriteCond %{REQUEST_FILENAME} !-d

# if $1 is empty
RewriteCond $1 ^$ [OR]

# if $1 is not an existing file
RewriteCond %{DOCUMENT_ROOT}/$1 !-d

# (?!en/) is a negative lookahead to assert we don't already have /en/ at start
# ([^/]+/)? captures an optional match before first / into $1
# $0 represents full match here that is between ^ and $
# /en/$0 prefixes /en/ before current Request URI
RewriteRule ^(?!en/)([^/]+/)?.*$ /en/$0 [R=301,L,NC]

我可能没有说明根目录下还有其他子目录,我仍然需要保持访问权限,例如
https://example.com/zh/
https://example.com/hub/
。此外,您建议的规则会导致重定向循环。最后,我不想保持URL不变。我也需要换一下。我不介意使用“重定向匹配”规则。再次抱歉我的错误。请重写规则,以便在子目录不存在时也重定向该规则,好吗?(见上面我的问题更新)谢谢!我的一天就这样完了!非常感谢!最后,还有几个问题:1。这里的“$0”代表什么?除了“1美元”,我从未用过它。2.你能解释一下正则表达式在这里的作用吗?谢谢我在规则中增加了解释。