Internet · June 4, 2023 0

TimThumb Thumbnail URL Rewrite Rule for Nginx & Apache

Haven’t update my blog post for a long time, as a result, I did not notice that the SSL certificate of my blog was overdue. That carelessness made my blog offline for days. While configuring the SSL certificate, I noticed that the requests from timthumb.php were a great amount of number. So an idea came up straightforoward, why not customize these thumbnail URLs to a pretty one? With URL rewriting, thumbnails can also be cached by Cloudflare or other CDNs, which could reduce a lot of requests from the timthumb.php file. By the way, I really miss the days of enjoying Upyun and Qiniu CDN’s services.

Timthumb URL Rewrite Rules for Nginx

To customize the thumbnails’ URLs to pretty ones’, the key is this rewrite rule. I searched for a lot of rules, but most of them did not work at all. Finally, I found a good one in Bugxia’s post. Thanks for his selfless dedication.

rewrite "^(.*)/thumb/(.+?)/(.+?)/(.+?)/(.+?)/(.+?)$" /wp-content/themes/Git-alpha/timthumb.php?src=$6&h=$2&w=$3&q=$4&zc=$5 last;

With this Nginx rewrite rule for timthumb, most of you guys should know how to do it next. However, for me and other fish users, it is still confusing. So I will make some explanations.

The first (.*) , please do not modify it. It is the root of the document. And there should be a $1, which I omitted, coming up with the second URL.

/thumb/ is a virtual subfolder for thumbnails and you can change the name as you like or just remove it.

/(.+?)/ There are 5 symbols like this. They are corresponding to $2 ~ $6 in the rules. If you have X number of (.+?) symbols, then there should have X number of $x (x should be numeric begin with 2). In this rule, the symbol of “/” means a folder level, you can reduce the folder to /(.+?)(.+?)(.+?)/(.+?) or someone like this.

/wp-content/themes/Git-alpha/timthumb.php should be your theme’s timthumb file location. Please rename Git-alpha to your own theme’s name if you use WordPress like me.

src=$6&h=$2&w=$3&q=$4&zc=$5 These are Timthumb’s crop image rules.
src=$6 means the real image’s URL.
h=$2 means thumbnails’ height.
w=$3 is the thumbnail’s width.
q=$4 stands for the quality of the thumbnail image.
And zc=$5 is the strategy of how to crop the image.
All these specifications should follow your theme rule or it won’t work.

After configuring the Nginx rewrite rule for Timthumb. Let’s see if it works. For example

However, when you visit this image, it returns an error like this.

The thumbnail’s URL are missing one / character. To fix this issue, we can remove the address which is your domain name.

Update Theme’s Thumbnail Fetching Code

If you are using TimThumb, then the thumbnail fetching code must exist in your theme’s Function.php or somewhere. Go find it and update it as below.

echo $post_thumbnail_src

Update it with…

echo str_replace("","", $post_thumbnail_src);

Be sure to replace with your own domain name. Then restart Nginx / PHP / Memcached service.

Below is the demo code of fetching thumbnail in my theme.

//Fetching and output thumbnail
function post_thumbnail_src() {
    global $post;
    if ($values = get_post_custom_values("git_thumb")) { 
        $values = get_post_custom_values("git_thumb");
        $post_thumbnail_src = $values[0];
    } elseif (has_post_thumbnail()) { //If there is featured thumbnail, output thumbnail
        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID) , 'full');
        $post_thumbnail_src = $thumbnail_src[0];
    } else {
        $post_thumbnail_src = '';
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
        @$post_thumbnail_src = $matches[1][0]; //Fetching image's src
        if (empty($post_thumbnail_src)) { //Show random image if there is no image in the post.
            $random = mt_rand(1, 12);
            //echo GIT_URL;
            echo 'wp-content/themes/Git-alpha/assets/img/pic/' . $random . '.jpg';
   // echo $post_thumbnail_src;
   echo str_replace("","", $post_thumbnail_src);

Update Theme’s Thumbnail Code to URL Rewrite One

After you have done the upper 2 steps, you may need the last step to make it work as expected. We need to update the dynamic thumbnail src to a URL-rewritten src. The demo code is the theme of Git’s usage.

else {
            echo '<img class="thumb" '.$src.'="' . GIT_URL . '/timthumb.php?src=';
            echo post_thumbnail_src();
            echo '&h=273&w=856&q=90&zc=1&ct=1" alt="' . get_the_title() . '" />';

Then we need to update is to

else {
            echo '<img class="thumb" '.$src.'="./thumb/273/856/75/1/';
            echo post_thumbnail_src();
            echo '" alt="' . get_the_title() . '" />';

Now everything is done. Let’s see if it works. If it works, that’s great. However, the thumbnails are still requested dynamically. It still consumes a lot of service resources. We can force CDN servers to cache these files to reduce dynamic requests.

Thumbnail With CDN

If you are using Cloudflare CDN, you can find the how to here.

Timthumb URL Rewrite Rule for Apache

<IfModule mod_rewrite.c >
RewriteEngine On
RewriteBase / 
RewriteRule ^(.*)/thumb/(.*)/(.*)/(.*)/(.*)/(.*)   $1/wp-content/themes/Git-alpha/timthumb.php?src=$6&h=$2&w=$3&q=$4&zc=$5

Please update rewrite base folder according to where you store .htaccess file. And the rest rules can be updated like Nginx one.