Apache根目录重定向至子目录并保留请求路径的配置咨询
Solution for Your Apache Redirect Needs
Got it, let's tackle this redirect problem properly. The key here is to target all paths that don't already start with /zh/, /hub/, or /en/ and send them to the /en/ prefixed version, while leaving your existing subdirectories untouched.
Option 1: Using RedirectMatch (as you requested)
This is clean and uses Apache's mod_alias module. Add this to your .htaccess file or Apache config:
RedirectMatch 301 ^/(?!zh/|hub/|en/)(.*)$ /en/$1
Let's break down the regex:
^/matches the start of the URL path (right after the domain)(?!zh/|hub/|en/)is a negative lookahead—it ensures the path doesn't start with any of those three subdirectories(.*)captures the rest of the path (including empty string for the root domain)/en/$1appends the captured path to the/en/prefix
This will handle all your cases:
https://example.com/abcde→https://example.com/en/abcdehttps://example.com/abcde/edgs→https://example.com/en/abcde/edgshttps://example.com/→https://example.com/en/- And it leaves
https://example.com/zh/xxx,https://example.com/hub/yyy,https://example.com/en/zzzcompletely untouched.
Option 2: Using mod_rewrite (more flexible if you need additional rules later)
If you're already using mod_rewrite elsewhere, this might fit better. Add this to your .htaccess:
RewriteEngine On # Skip redirect for existing subdirectories RewriteRule ^(zh|hub|en)/ - [L] # Redirect all other paths to /en/ prefix RewriteRule ^(.*)$ /en/$1 [R=301,L]
Notes for testing:
- Start with
R=302(temporary redirect) instead of301first—301 redirects get cached by browsers, which can make testing changes a pain. Once you confirm everything works, switch to301. - Make sure either
mod_alias(for RedirectMatch) ormod_rewriteis enabled on your Apache server. Most hosting providers have these enabled by default, but if not, you'll need to enable them via your server config.
内容的提问来源于stack exchange,提问作者EagleTheDev
相关产品推荐
相关产品推荐

