Apache将root重写为子目录并保留request_uri

时间:2018-01-10 15:05:06

标签: apache .htaccess mod-rewrite

我想将https://example.com/abcdehttps://example.com/en/abcdehttps://example.com/acefr的网址重写为https://example.com/en/acefr

我尝试过这样的事情:

RewriteRule ^$ /en [R=301]

它可以将我从https://example.com/重定向到https://example.com/en/;但是当我的网址为https://example.com/abcde时,它会保留原始网址。

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

非常感谢!

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

最后,我不想保持URL不变。我也需要改变它。我不介意使用'RedirectMatch'规则。

为了更好地理解:

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)

谢谢!

1 个答案:

答案 0 :(得分:1)

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

# 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]

确保在测试前清除浏览器缓存。

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

NavigationView