I was working on developing the demo app to produce the next article in this series, when I ran across a CORS problem. I wanted to read my blog feed from a client-side application. Obviously that did not go very well, since WordPress does not allow cross-site requests by default.

The solution presented in this article will probably work with any web application in Azure. Not just WordPress.

WordPress on Azure

I’m running my WordPress blog in Azure. Yes, I know. There are a lot cheaper options for WordPress hosting. But hey, I’m an Azure fan boy too, so what can you do 😉

The first thing that always comes to mind when you need to modify your WordPress site is that there must be a plugin for that. I found several plugins that advertised that they allow you to modify the response headers. That’s what you need to do to enable CORS on any website, web application or API.

So after trying a few of these plugins, I realized that it won’t work. There must be something related to hosting WordPress on IIS that prevents the plugins from working.

App Service Editor to the Rescue

After the few attempts with the plugins, I turned to the Azure management portal. I’ve been configuring CORS quite a few times for Azure Function apps, so I thought why not on web apps too? Turns out that there’s no CORS settings for web apps. They are just for function and API apps.

So I dug a bit deeper into the back of my mind, and remembered that there’s actually a lot you can configure in web.config for a web application. You basically need to make sure you have the following configuration in your web.config file. The most important line is highlighted.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

The easiest way to do this is with the App Service Editor, which is still in preview (Early January 2020). To find it, you navigate to your web application on the Azure management portal, and scroll down to Development Tools, where you’ll find the App Service Editor.

If you already have a web.config file in the root of your web application, then you just need to merge the config above to the existing file. If the file does not exist, you need to create it.

After this, my blog started to send the Access-Control-Allow-Origin header, and my client-side application was able to access my blog feed.

By the way, if you’d like to host your WordPress site on Azure, click here to get started.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *