在您的文档根目录中尝试这样的操作:
RewriteEngine On
# check if subdomain folder has the existing file, if so, serve it
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -f
RewriteRule ^(.*)$ /%1/$1 [L]
# check if subdomain folder has the existing directory WITH A TRAILING SLASH, if so serve it
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -d
RewriteRule ^(.*?)/$ /%1/$1/ [L]
# check if subdomain filder has the existing directory but missing trailing slash, redirect with it
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -d
RewriteRule ^(.*)$ /$1/ [R=301,L]
这个方法为你做了两件事,如果是 404,它不会尝试在内部重写,所以如果你去:http://sub.domain.co.uk/this/path/does/not/exist/blah
,你不会收到 404 消息说:/sub/this/path/does/not/exist/blah
不存在,只是/this/path/does/not/exist/blah
因为 URI 是' t 重写,因此不会暴露您的底层目录结构。
第二件事是你可能已经DirectorySlash
打开了。这意味着如果您访问类似的目录:http://sub.domain.co.uk/this/path
,缺少尾部斜杠, mod_dir 将希望重定向并添加该斜杠,但它可能会做错,因为 URI 已被重写并将您重定向到:http://sub.domain.co.uk/sub/this/path/
。我们先发制人地添加带有正确 URI 的尾部斜杠,隐藏sub
.