.htaccess子目录下的子域



我正在构建一个应用程序,我想将子域'x'映射到example.com/_sub/x/,但前提是文件夹'x'存在于文件夹'_sub'中。如果没有,我希望显示example.com。下面的工作,但只有当文件或文件夹也存在于文件夹x中。

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^(.*).example.com [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ http://example.com/_sub/%1/$1 [L]
</IfModule>

这是另一种看待它的方式。

doesNotExist.example.com -> example.com
test.example.com         -> test.example.com
example.com              -> example.com

这是我更新的代码。

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
#If the file and directory exists
RewriteCond %{HTTP_HOST} ^(.*).example.com [NC]
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/ -d
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/$1 -f
RewriteRule ^(.*)$ http://example.com/_sub/%1/$1 [P]
#If the directory exists but the file does not
RewriteCond %{HTTP_HOST} ^(.*).example.com [NC]
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/ -d
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/$1 !-f
RewriteRule ^(.*)$ http://example.com/_sub/%1/404.html [P]
</IfModule>

我最初遇到的问题通过添加第二组规则来解决,将不存在的文件发送到本地404页面。一旦我弄明白了这一点,我就发现除了没有尾随文件的链接之外,其他一切都可以正常工作。我只是添加了[OR]语句和下面的行来解决这个问题。希望这篇文章能对像我这样处境的人有所帮助。

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
# If the file and directory exists
RewriteCond %{HTTP_HOST} ^(.*).example.com [NC]
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/ -d
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/$1 -d
RewriteRule ^(.*)$ http://example.com/_sub/%1/$1 [P]
# If the directory exists but the file does not
RewriteCond %{HTTP_HOST} ^(.*).example.com [NC]
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/ -d
RewriteCond %{DOCUMENT_ROOT}/_sub/%1/$1 !-f
RewriteRule ^(.*)$ http://example.com/_sub/%1/404.html [P]
</IfModule>

最新更新