如果找不到文件/图像,则 modrewrite 到另一台服务器
您好,我正在开发远程站点的本地服务副本,我不想下载与该站点相关的所有图像,所以我想我可以提出一个 mod_rewrite 规则来从远程服务器获取图像,如果未找到
我想将任何会导致 404 的图像请求重定向到远程服务器 即类似这样的内容:
^localpath(.*) http://otherhost/localpath$1
这是我的代码
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [NC]
RewriteRule ^/(.*\.(png|gif|jpg|jpeg)) https://www.exmple.com/$1 [NC,P,L]
</IfModule>
该页面仍然为我提供远程服务器上图像的 404,因此该规则不起作用。
我确实知道 htaccess 正在被处理,因为 IfModule mod_rewrite.c 块后面的规则正在被使用。 (我简化了代码示例,但这是 IfModule mod_rewrite.c 块中的第一条规则)
编辑 此代码用于重定向所有 404
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.+) https://www.example.com/$1 [L]
Hi I am working on a locally served copy of a remote site and I don't want to have to download all the images rtelated to the site so I thought i could come up with a mod_rewrite rule for to grab images from the remote server if the are not found
I want to redirect any image request that would result in a 404 to the remote server
ie something like this:
^localpath(.*) http://otherhost/localpath$1
this is the code that i have
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [NC]
RewriteRule ^/(.*\.(png|gif|jpg|jpeg)) https://www.exmple.com/$1 [NC,P,L]
</IfModule>
The page is still giving me 404's for images that are on the remote server, so this rule is not working.
I do know that the htaccess is being processed because rules later in the IfModule mod_rewrite.c block are being used.
(i simplified my code sample but this is the first rule in the IfModule mod_rewrite.c block)
edit
This code works to redirect all 404's
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.+) https://www.example.com/$1 [L]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
RewriteCond
中应该有!-f
,以便该规则适用于不存在的文件。另外
$1
只是文件扩展名,因为该组将首先被解析。我认为您想要$2
。子文件夹中的文件在 RewriteRule 中不以 / 开头,因此您可能也想从匹配模式中删除它。
You should have
!-f
in yourRewriteCond
so the rule applies to files which don't exist.Also
$1
will be just the file extension because that group will get parsed first. I think you want$2
.Files in subfolders don't start with / in the RewriteRule so you probably want to remove that from your match pattern as well.