我很有兴趣在重写规则中修改一些url和路径。这里有一些例子。
我有一些主机名通过Apache conf中的ServerAlias查找到1个VirtualHost。
example.com
anotherdomain.com
same.org
还有很多其他的域名。在这里,我想做什么:
example.com/uploads/photo.png -> /www/example.com/uploads/example.com/photo.png<br />
anotherdomain.com/uploads/photo.png -> /www/anotherdomain.com/uploads/anotherdomain.com/photo.png<br />
与其他域名相同。这件事我已经做过了。
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._]+)$ uploads/%2/$1 [L]
这项工作完美无缺。但是,如果我尝试访问uploads / icons / category / image.png
我开始看到500内部Apache错误......
我已将Rule修改为:
RewriteCond %{REQUEST_URI} !^/uploads/%{HTTP_HOST}
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._/]+)$ uploads/%2/$1 [L]
启用Apache重写日志,详细程度为9。
RewriteCond: input='/uploads/icons/category/image.png' pattern='!^/uploads/%{HTTP_HOST}' => matched
rewrite 'uploads/icons/category/image.png' -> 'uploads/example.com/icons/category/image.png'
RewriteCond: input='/uploads/example.com/icons/category/image.png' pattern='!^/uploads/%{HTTP_HOST}' => matched
rewrite 'uploads/example.com/icons/category/image.png' -> 'uploads/example.com/example.com/icons/category/image.png'
之后,它耗尽了10次查找=(
当我修改为
RewriteCond %{REQUEST_URI} !^/uploads/example.com
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._/]+)$ uploads/%2/$1 [L]
它适用于所有内容,但仅适用于1个域:example.com
我找到了另一种解决方案,但它并不完美。
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._/]+)$ uploads/%2/$1 [L]
此规则仅在我存在dir和file时才有效。但是,如果我试图访问:
/uploads/images/not-existed-404.nothing
- &gt;它返回500,因为该文件不存在并重写为:
/uploads/example.com/example.com/example.com/example.com.......
P.S。抱歉我的英语不好;)
答案 0 :(得分:4)
RewriteCond %{REQUEST_URI} !^/uploads/%{HTTP_HOST}
您不能在模式中使用变量或反向引用 - 即%{HTTP_HOST}
不会扩展为example.com
,而是将其视为普通文本。
您可以使用这些规则(在我的电脑上正常工作):
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteCond %{DOCUMENT_ROOT}/uploads/%2/$1 -f
RewriteRule ^uploads/(.+)$ uploads/%2/$1 [L]
此规则将检查目标文件是否存在,然后重写(条件顺序重要)。
我们假设:
example.com
/www/example.com/
/uploads/img/meow.png
第二个条件(RewriteCond %{DOCUMENT_ROOT}/uploads/%2/$1 -f
)将检查文件/www/example.com/uploads/example.com/img/meow.png
是否存在,如果存在,则进行重写。
你的.htaccess可能看起来像这样:
RewriteEngine On
RewriteBase /
# do not do anything for already existing files & folders
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]
# rewrite uploads to domain-specific folder
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteCond %{DOCUMENT_ROOT}/uploads/%2/$1 -f
RewriteRule ^uploads/(.+)$ uploads/%2/$1 [L]