Setup Caching on your Azure Storage Blobs

Azure Blob Storage can be used for publishing files to the web. Actually, this website is using Azure Blog Storage for publishing images and other resources. They each get an URL for direct access from any web browser. However, it is good practice and good for performance to setup caching on images and web resources. Here I will describe how.

By setting the Public access level on your Storage Container to "Blob", your blobs will be available to everyone through their URLs. You can link to them and use them from any website.

Azure Storage Container Access Level

Unfortunately the Azure Portal don't allow access to the caching settings of the blobs. There is no such thing in the Blob Properties shown.

Azure Storage Blob overview

Luckily, you can easily run scripts in the Azure Portal.

Using Cloud Shell for Setting the Blob Caching

Azure Cloud Shell enables you to easily run PowerShell- or Bash-script from within the Azure Portal. Open it and choose Powershell mode.

Azure Portal Cloud Shell

Next, copy the script below to a text editor. Update the settings and paste it into Cloud Shell. max-age is measured in seconds. For a complete description of the cachecontrol options, see here.

 1$resourcegroup = "your resource group"
 2$account = "your storage account"
 3$container = "your container"
 4$cachecontrol = "public,max-age=259200" # 3 days
 5
 6Set-AzCurrentStorageAccount -ResourceGroupName $resourcegroup -Name $account
 7$blobnames = (Get-AzStorageBlob -Container $container).Name
 8
 9Foreach ($blobname in $blobnames)
10{
11  Write-Host $blob.Name
12  $blob = Get-AzStorageBlob -Container $container -Blob $blobname
13  $blob.ICloudBlob.Properties.CacheControl = $cachecontrol
14  $blob.ICloudBlob.SetProperties()
15}

You can also read all cache settings in a similar way:

 1$resourcegroup = "your resource group"
 2$account = "your storage account"
 3$container = "your container"
 4
 5Set-AzCurrentStorageAccount -ResourceGroupName $resourcegroup -Name $account
 6$blobnames = (Get-AzStorageBlob -Container $container).Name
 7
 8Foreach ($blobname in $blobnames)
 9{
10  $blob = Get-AzStorageBlob -Container $container -Blob $blobname
11  Write-Host $blob.Name $blob.ICloudBlob.Properties.CacheControl
12}
Testing

You should now be able to test the caching from any web browser:

Web Browser view caching

Good luck!

Related Posts