我在 中有一个包罗万象的 Apache 虚拟主机/var/www/
。其中,我有一个index.php
用于处理所有页面代码的文件夹,以及保存每个站点资源(图像、css 等)的子文件夹。
我想要一个重写,如果子文件夹中存在相应域的图像,则使用它们,如果index.php
不存在,则将其移交给子文件夹。我也不想直接访问这些子文件夹。
例子
http://example.com/images/fb.png-> /var/www/sites/example.com/images/fb.png http://example.com/sites/example.com/images/fb.png-> /var/www/index.php (显示 404) http://example.com/whatever-> /var/www/index.php
看起来很简单,但我不知道如何阻止/sites/
。
.htaccess
这种方法除了允许http://example.com/sites/example.com/images/fb.png
直接访问外,其他都有效。
RewriteCond %{REQUEST_URI} !^/sites/
RewriteRule ^(.*)$ sites/%{HTTP_HOST}/$1 [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php
痕迹
[rewrite:trace3] [/initial] [perdir /var/www/] add path info postfix: /var/www/images -> /var/www/images/fb.png
[rewrite:trace3] [/initial] [perdir /var/www/] strip per-dir prefix: /var/www/images/fb.png -> images/fb.png
[rewrite:trace3] [/initial] [perdir /var/www/] applying pattern '^(.*)$' to uri 'images/fb.png'
[rewrite:trace2] [/initial] [perdir /var/www/] rewrite 'images/fb.png' -> 'sites/example.com/images/fb.png'
[rewrite:trace3] [/initial] [perdir /var/www/] add per-dir prefix: sites/example.com/images/fb.png -> /var/www/sites/example.com/images/fb.png
[rewrite:trace3] [/initial] [perdir /var/www/] add path info postfix: /var/www/sites/example.com/images/fb.png -> /var/www/sites/example.com/images/fb.png/fb.png
[rewrite:trace3] [/initial] [perdir /var/www/] strip per-dir prefix: /var/www/sites/example.com/images/fb.png/fb.png -> sites/example.com/images/fb.png/fb.png
[rewrite:trace3] [/initial] [perdir /var/www/] applying pattern '.' to uri 'sites/example.com/images/fb.png/fb.png'
[rewrite:trace2] [/initial] [perdir /var/www/] strip document_root prefix: /var/www/sites/example.com/images/fb.png -> /sites/example.com/images/fb.png
[rewrite:trace1] [/initial] [perdir /var/www/] internal redirect with /sites/example.com/images/fb.png [INTERNAL REDIRECT]
[rewrite:trace3] [/initial/redir#1] [perdir /var/www/] strip per-dir prefix: /var/www/sites/example.com/images/fb.png -> sites/example.com/images/fb.png
[rewrite:trace3] [/initial/redir#1] [perdir /var/www/] applying pattern '^(.*)$' to uri 'sites/example.com/images/fb.png'
[rewrite:trace3] [/initial/redir#1] [perdir /var/www/] strip per-dir prefix: /var/www/sites/example.com/images/fb.png -> sites/example.com/images/fb.png
[rewrite:trace3] [/initial/redir#1] [perdir /var/www/] applying pattern '.' to uri 'sites/example.com/images/fb.png'
[rewrite:trace1] [/initial/redir#1] [perdir /var/www/] pass through /var/www/sites/example.com/images/fb.png
我不明白 mod-rewrite 及其循环结构... 我很想得到一些帮助。Mod-rewrite 似乎总是给我带来麻烦。
答案1
这就是我想要的。
# rewrite to site subfolder
RewriteRule ^(.*)$ sites/%{HTTP_HOST}/$1 [NC,QSD,DPI]
# if file doesn't exists in subfolder, just pass it to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [END]
# prevent another go-around
RewriteRule .* - [END]