简体   繁体   中英

Redirect all image urls to my CDN - Wordpress

I'm using a CDN for serving my images on my Wordpress..

The URL structure goes as such:

//mydomain.com/assets/uploads/[year]/[month]/[day]/[imagename].png or whatever

For my CDN the images are served as:

//cdn.cdnnetwork.com/mydomain.com/assets/uploads/[year]/[month]/[day]/[imagename].png or whatever

Now the problem is that whenever the image gets accessed directly either with typing in the exact url or a search engine redirecting it they all go to:

//mydomain.com/assets/uploads/[year]/[month]/[day]/[imagename].png or whatever

I want to use .htaccess rule or any other way to redirect all

//mydomain.com/assets/uploads/[year]/[month]/[day]/[imagename].png or whatever

links to:

//cdn.cdnnetwork.com/mydomain.com/assets/uploads/[year]/[month]/[day]/[imagename].png or whatever

So I can save bandwidth... Is it possible? The images embedded in a actual webpage using the img tag are fine it's just direct access to the images.

This should be doable. Your .htaccess file (in www root) would look something like this:

RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=proto:https]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=proto:http]

RewriteCond %{HTTP_HOST} ^mydomain.com/assets$
RewriteRule ([^.]+\.(jpe?g|gif|bmp|png))$ %{ENV:proto}://cdn.cdnnetwork.com/mydomain.com/$1 [L,R=301]

See this answer for more information on how to preserve the protocol (http/https): Preserve HTTP/HTTPS protocol in .htaccess redirects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM