Reputation: 5
I am using Youtube video IMG.
Example link: https://i.ytimg.com/vi/aSVpBqOsC7o/hqdefault.jpg
I would like: http://cdn.mywebsite.com/vi/aSVpBqOsC7o/hqdefault.jpg
How can I do it with PHP and .htaccess?
Upvotes: 0
Views: 50
Reputation: 42885
The apache http server comes with great modules, among those is the proxy module. It offers exactly what you are looking for without the need of some scripting language or similar:
The simple and direct approach is to proxy the whole URL https://i.ytimg.com/vi/
inside your own domain space:
ProxyRequests off
ProxyPass /vi/ https://i.ytimg.com/vi/
For the documentation see: https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#proxypass
Another apporach that offers more flexibility is to use the proxy module from within the rewrite module:
RewriteEngine on
RewriteRule ^/?vi/([^/]+)/(.+)$ https://i.ytimg.com/vi/$1/$2 [L,P]
For the documentation see: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule
The same effect as the first approach can also be reached by a notation which is limited to the host configuration:
ProxyRequests off
<Location /vi/>
ProxyPass https://i.ytimg.com/vi/
</Location>
Both upper approaches can be used inside the http host configuration or, if really necessary, inside dynamic configuration files (.htaccess
style files). In general you should always prefer to place such rules in the host configuration. .htaccess
style files add complexity, are notoriously error prone, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).
Upvotes: 1