Friday, January 14, 2022

[FIXED] Automatically changing URL references from an internal source to an external one

Issue

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

e.g. mywedomain.com/images/myimage.jpg, where mywebdomain.com/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!


Solution

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.



Answered By - Orbling

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.