Codementor Events

Redirect www to non-www with Azure serverless function (Linux server)

Published Feb 09, 2022
Redirect www to non-www with Azure serverless function (Linux server)

Photo credit: https://chsakell.com/2018/11/18/building-serverless-apps-with-azure-functions/

Recently, I had to redirect a website from www to non-www.
This simple operation turned out to be much more complex than it seemed to be.
For a series of reasons related to the architecture and the hosting provider we are working with, I ended up choosing Azure Serverless function to do the redirect.
If you are interested to know more about the decision that brought me to choose Azure Serverless Function, you can read about it here.

It was my first time writing a serverless function in Azure, actually was the first time I wrote a serverless function at all.
Online, I found lots of resources on how to do it in a Windows server with C# or .Net code samples but very little information on how to create it for a Linux server with Node.js.
It turns out creating a serverless function for Windows and Linux has quite different settings and workflow.I lost lots of time in figuring out how to create and upload the function to Azure, therefore I’m writing this step-by-step tutorial in the hope to save someone else’s time.

What is a serverless function?

It was the first time for me to work with a serverless function. Even If I have already heard and read about it, I never took the time to understand them properly. Therefore, that was my first step.

A serverless function is a simple function written by a developer and hosted on a cloud computing company or IaaS.

Cloud computing companies are companies that provide all the physical (and non) infrastructure needed to support a computing environment.
These companies are often called “serverless”.
Indeed they still use a physical server to execute code but they abstract the server (and other infrastructure) away so that the developer can focus just on their code, working faster and easier.
One of these serverless companies is Azure.

Is important also to say that a serverless function is a stateless function (cannot hold data in it), is a used-and-destroy kind of function (non-permanent) and it accomplishes one single task, for example, redirecting a website from www to non-www.

How does it work?

Once I understood what a serverless function and its environment is, I was curious to understand how does it work.
Azure functions are event-driven, which means the function will start through an event (or action). Each event has a specific trigger to execute the function.
There are several triggers; one of those is the HTTP trigger: Receiving an HTTP request. And that’s the one we need for our redirect.

So how does a www redirect serverless function work in Azure?
Once the function is created on Azure Portal, an IP address for this function is created.
Then it just needs to point the DNS of a website to this IP address, in this way the HTTP trigger will execute the function whenever someone simply visits the website.
Ok, this starts to make sense to me.
Let’s see in detail how to do that.


Creating Azure Serverless Function in Azure Portal

1_ Create Function App from Azure Portal

Head to https://portal.azure.com and create a new resource.
Here, pick Function App.
Function app is a single application. It can host several functions.
1*vV9_QLIZGFdEK5dvDNM3AQ.jpeg

Have a look at <Hosting> or <Networking> tabs and set up them as you need.
If you are unsure, the default settings should be good enough.
Once you validate, create, and deploy your new resource, click on <Go to Resource> and you should end up in the Overview screen of your newly created Function App.
1*9xhQfdGQEmHmRR6kxLaNxA.jpeg

1*jCIJaIgLkzTlUmRJRyuEaw.jpeg

Two things to notice here: we got an URL (you see it on the Overview screen) and an IP address (you can find it in Custom Domains, in the side menu). These are bind to the Function App, not the function in itself.

2_ Create the serverless function from the portal

On the side menu in Azure Portal Function App, there is <functions>. Let’s go there.
Find the <create> button here, click on it and it will open a new screen where we can create the function.

Here we see the main difference between Windows and Linux servers.
On Windows server, in the dropdown menu, we have the option to “Develop on portal”.
On Linux, we do not have this option. There is even a warning message on the main screen telling us “Editing functions in the Azure portal is not supported for Linux Consumption Function Apps.”
Sadness.

0*909pWhb2tTIVGKlM
0*AGHmhEjxqNPYcIF-

We can choose between VS Code or any other editor. Picking one of these choices will give some instruction on how to deploy the function.
Let’s see in detail how we can create and deploy it.


Creating the function on Visual Studio Code

We will now create a function on our code editor and then upload it (or deploy it) to Azure.
With Visual Studio Code is very easy.
There is an Azure Functions extension which we can login to Azure, sync with code on Azure and most importantly, to easily deploy code to Azure.

1_ Install and configure Azure Function extension

  • First thing is to install the extension for Visual Studio Code.
  • Now on the left side menu, you should get a new item which is the Azure logo. Click on it and you should see an option to Sign in to Azure.

0*7l6BprUbGc7wms8T

  • Clicking on Sign-in will redirect you to a browser page where you will need to login into your Azure account. After that you should be able to see a message of successful login. You can now close the browser tab and go back to Visual Studio Code.

At this point, instead of ‘Sign in to Azure’ you should see your Azure Subscriptions.
If you have other functions on your Azure Function App, they will show up here. The code is read-only tho.

2_ Create the function locally

To create our redirect function we will need to create a new Local Project. Click on the “create function” icon
0*U5heknc23G-cXg-h.png

  1. If it is your first function it will ask you to select an empty folder to create your project in it.

  2. After that, you need to select your favorite programming language. I will write my function in Node.js so I pick Javascript.

  3. It will ask you if you want to create the function from a template. These are the triggers we talked about before. For our purpose, we pick the HTTP Trigger. After that, it asks you to give a name to your function. Pick the name you like more, in my case I picked “redirect-func”

  4. And to finish, it will ask you which authorization level you want.

    • Anonymous: every time the function URL is hit, the function will run without further authentication.
    • Function: the function URL will have a token as a parameter. Without it, the function is not executed.

For a simple implementation, we can pick Anonymous.

And we are done. An <index.js> file should open automatically.
Go to the Explorer menu from Visual Studio Code. You should see a folder with the function name. Inside of it you will find these two files: function.json and index.js.

We can finally start coding!


Coding, testing and deploy

1_ Code

Let’s open <index.js>. Here there is a sample code, we can delete it and add our redirect function:

// index.js
  
module.exports = async function (context, req) {
  context.log(‘The function is running’)
  
  var res = {    
  	status: 302,    
  	headers: {      
  		Location: ‘https://mydomain.com',    
  	},    
  	body: ‘Redirecting…’,  	
  }  
  
  context.res = res
}

This is a simple function that will take whatever request and it will respond with a redirect to a location specified in headers.location.
This function will be call from a www domain. Therefore it redirects to a non-www domain.

2_ Test and deploy

  1. Simply press F5 or click on the <Run and Debug> icon of Visual Studio Code menu.
    0*Suhc3-vm3Sbvd7Cr

  2. Go to the Azure Function extension, double click on the function, and select <Copy Function Url>.
    1*EB0RiwJlQRpRO6w8BSwKZA.jpeg

  3. Navigate to a browser and paste the URL. You should be redirected to the domain you add in “headers.Location”.
    In my case, it is: https://mydomain.com

  4. You can now stop the local server from running clicking the <Disconnect> button (red button)
    0*TcaihOQWBOmmedzI

If everything works, we can finally deploy the function to Azure.
We do that simply by hitting the deploy button on Azure Function extension:
1*vdzFrqvDlm-jYymgZEdKnQ.jpeg

A proxy to call the function from root

Let’s head to the Azure portal, to the Function App resource.
Do you remember when we created the Function App we also notice an URL? Great, with this URL we can test the redirect function.

But when I pasted in my browser the Function App URL — https://redirect.azurewebsites.net — it did not work.
With surprise I realize the function is not under the root domain of the given URL but in a different path.
If my Azure Function URL is reachable at https://redirect.azurewebsites.net, the function in itself is reachable under https://redirect.azurewebsites.net/api/redirect-func.
This now makes sense, if I have multiple functions, each one of them needs its own location.

But this created a new issue: If I point my domain DNS to https://redirect.azurewebsites.net, it will not call the redirect function.
I had to find a way to call the function every time the root domain was hit.
After quite a lot of research on the web, I decided to use a proxy. I will proxy any request to redirect.azurewebsites.net to the azure function path URL.
Let’s see how to do it.

In Azure Function App, on the side menu, we can find a proxy item.

Once again, is not possible to edit Proxy directly in the Azure portal so we need to create a local file once again.

  1. Go to your local project in Visual Studio Code, where we have written the redirect function. There, at the root level of your project folder, we can create a file called proxy.json
  2. Write the proxy code:
// proxy.json
{  
  “$schema”: “http://json.schemastore.org/proxies",
  	“proxies”: {      
  		“redirect”: {        
  		“matchCondition”: {          
  			“route”: “/”        
  		},        
  		“backendUri”: “http://redirect.azurewebsites.net/api/redirect-func"      
  	}  
}}

backendUri is the URL of the function, where we want to proxy our request.
macthContion is the route that should “activate” the proxy.

  1. To deploy the proxy we use the same way we used to deploy the function, using the deploy icon (It will deploy the whole function folder, so no need to specify which file we are deploying)

Now we should be able to go to http://redirect.azurewebsites.netand get redirected to the domain we added in the headers.location config of the serverless function.

DNS Connection

We can finally add the function URL to our website’s DNS and connect the two.
0*tudXCNHLq50WmW6K

SSL CERTIFICATE

Last but not least, we want the redirect to work either if we go to http://mywesbite.comor if we go to https://mywesbite.com.

To make it a secure connection the redirect function URL — http://redirect.azurewebsites.net — should have an SSL certificate.

You could add one from Azure Portal, in the TLS/SSL binding section of the Function App menu.
In my project, we bought an Azure certificate but without the wildcard, which means it supports the root domain mydomain.com and www.mydomain.com but none of the subdomain.

I then had a Free SSL certificate — I opted for https://letsencrypt.org/ — in PMX format since Azure accepts just that format.
Once this is done, you can change the proxy backendUri to HTTPS too.

Annnnnnnnd… finally www.mydomain.com redirect to mydomain.com with and without secure connection!
What a journey for a simple redirect operation like this one!

Discover and read more posts from giorgia sambrotta
get started
post commentsBe the first to share your opinion
Show more replies