DolDurma
DolDurma

Reputation: 17330

Html show image based on hashed url

Simply I want to show this image url which that's on instagram:

<img src="https://scontent-amt2-1.cdninstagram.com/v/t51.2885-19/s150x150/269430179_619307746060977_8863061929784384401_n.jpg?_nc_ht=scontent-amt2-1.cdninstagram.com&_nc_cat=109&_nc_ohc=ZuthlbGc4tYAX9H5CH4&edm=AEF8tYYBAAAA&ccb=7-4&oh=00_AT9NSiEkpQ91iKHZ9L7udb9lJ3pNtC0CR0pBAqpwhkPTHg&oe=61CD0C19&_nc_sid=a9513d" alt="">

when I try to show this image with the browser I don't have any problem and I can, but when I try to use HTML with IMG tag it can't appear, all of instagram images has hash or based on hash and we can't remove them,

How can I resolve this problem?

updated:

<ifModule mod_headers.c>
   Header set Access-Control-Allow-Origin: *
</ifModule>

Upvotes: 1

Views: 868

Answers (1)

anthumchris
anthumchris

Reputation: 9090

As @Tagi commented, Instagram is checking the HTTP Referer request header and blocks requests from third-party domains. This can be bypassed with server-side proxying. For example, Nginx can be configured to proxy the images with:

server_name example.com;

location ~ ^/instagram-image(.*) {
  proxy_pass https://scontent-amt2-1.cdninstagram.com$1$query_string;
  add_header Access-Control-Allow-Origin *;  # allows fetch() to succeed
  expires 1y;
}

Then, any requests to your "example.com" Nginx server would use the URI and query string to load the image from Instagram's domain:

https://example.com/instagram-image/v/t51.2885-19/s150x150/269430179_619307746060977_8863061929784384401_n.jpg?_nc_ht=scontent-amt2-1.cdninstagram.com&_nc_cat=109&_nc_ohc=ZuthlbGc4tYAX9H5CH4&edm=AEF8tYYBAAAA&ccb=7-4&oh=00_AT9NSiEkpQ91iKHZ9L7udb9lJ3pNtC0CR0pBAqpwhkPTHg&oe=61CD0C19&_nc_sid=a9513d
  ⮑ << opens >> https://scontent-amt2-1.cdninstagram.com/v/t51.2885-19/s150x150/269430179_619307746060977_8863061929784384401_n.jpg?_nc_ht=scontent-amt2-1.cdninstagram.com&_nc_cat=109&_nc_ohc=ZuthlbGc4tYAX9H5CH4&edm=AEF8tYYBAAAA&ccb=7-4&oh=00_AT9NSiEkpQ91iKHZ9L7udb9lJ3pNtC0CR0pBAqpwhkPTHg&oe=61CD0C19&_nc_sid=a9513d

An <img src="https://example.com/..."> tag will still fail, but you can use a fetch request to dynamically show the image using fetch():

showImage(
  document.querySelector('img'),
  'https://example.com/instagram-image/v/t51.2885-19/s150x150/269430179_619307746060977_8863061929784384401_n.jpg??_nc_ht=scontent-amt2-1.cdninstagram.com&_nc_cat=109&_nc_ohc=ZuthlbGc4tYAX9H5CH4&edm=AEF8tYYBAAAA&ccb=7-4&oh=00_AT9NSiEkpQ91iKHZ9L7udb9lJ3pNtC0CR0pBAqpwhkPTHg&oe=61CD0C19&_nc_sid=a9513d'
)

async function showImage(img, url) {
  const buffer = await (await fetch(url)).arrayBuffer()
  img.src = URL.createObjectURL(new Blob([buffer]))
}

Upvotes: 1

Related Questions