开发者

Automatically changing URL references from an internal source to an external one

开发者 https://www.devze.com 2023-02-07 07:31 出处:网络
I would like to set all image references (really just references to a specific folder), e.g. mywedomain.com/images/myimage.jpg, where mywebdomain.c开发者_运维技巧om/images/myimage.jpg would actually

I would like to set all image references (really just references to a specific folder),

e.g. mywedomain.com/images/myimage.jpg, where mywebdomain.c开发者_运维技巧om/images/myimage.jpg would actually point to mycdn.com/images/myimage.jpg.

But keep the internal reference in the code/markup itself. I am wondering how one would handle this?

Thx!


It depends if it is on the same server or not as to how exactly you should handle that.

If it is on the same server, and within the document root, it would be easiest with a rewrite, using mod_rewrite.

Inside your main directory .htaccess file:

RewriteEngine on
RewriteBase /

RewriteRule ^/images/(.+)$ /mycdn.com/images/$1 [L]

If it is not in the document root, or on another server, then a redirect might be easier.

RedirectMatch ^/images/(.+)$ http://mycdn.com/images/$1 

Though this will be noticeable on the client, if they were looking at the request log. If you want it to be transparent, then you could proxy the request on your server.

Create a PHP file (or other language you use, you mention LAMP, hence PHP).

<?php

$reqImage = $_GET['image'];
$mimeTypes = array('gif' => 'gif', 'jpg' => 'jpeg', 'jpeg' => 'jpeg',
                   'png' => 'png');

$matches = array();
if (preg_match("/^[-a-zA-Z0-9_]+\.(gif|jpg|png)$/", $reqImage, $matches)) {
   header('Content-Type: image/' . $mimeTypes[$matches[1]]);
   @readfile("http://mycdn.com/images/" . $reqImage);
} else {
   header('HTTP/1.0 404 Not Found');
}

exit;

Note the need to pass out the Internet media type when providing the image, as Apache will be expecting something different from a PHP file, and normally handles that for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号