Documentation

    Amazon Web Services

    Microsoft Azure

    RapidAPI

    APILayer

Last Update: 2024-08-14

Self-Hosted URL Shortener


Table of Content


Subscribe on AWS Marketplace
Deploy your URL Shortener
Use your own Domain
API endpoint: Shorten
API endpoint: Remove
API endpoint: List
API endpoint: Track
Troubleshooting

Subscribe on AWS Marketplace


Navigate to our product listing on the AWS Marketplace. Select the "View purchase options" button to proceed.

On the following page, select "Deployment" as the contract option.

Next, click "Create contract" and then "Pay now".

To begin the deployment process, click on "Set up your account."

Please create an account on our website by clicking "Log in or create an account." This allows us to identify you and ensure you receive the necessary support.

On the next page, enter your name and email address, then click "Subscribe." You are now ready to deploy your application.

Deploy your URL Shortener


Ensure you have followed the steps above to subscribe to the AWS Marketplace listing and confirm that you have the required AWS permissions to deploy the CloudFormation stack.

To start the deployment, click on "Launch template."

Currently, only deployment in the AWS region "us-east-1" is supported. Ensure this region is selected, then click on "Launch template."

On the CloudFormation page, choose a name for your stack and acknowledge that AWS CloudFormation will create IAM resources. Then, click on "Create stack."

The CloudFormation stack is now deploying. Due to the deployment of a CloudFront distribution, this process can take up to 30 minutes to complete. Wait until the stack status changes to "CREATE_COMPLETE."

Once the stack has been successfully created, your URL shortener website will be available at the URL of the created CloudFront distribution. To obtain this URL, open the CloudFront console at https://us-east-1.console.aws.amazon.com/cloudfront/v4/home?region=us-east-1#/distributions.

You can now access the URL shortener website using this URL. Please refer to the chapter below for instructions on how to configure your own domain.

To obtain the necessary API key, go to the API Gateway console at https://us-east-1.console.aws.amazon.com/apigateway/main/api-keys?api=unselected&region=us-east-1 and find the key there.

To get the URLs for the API endpoints, go to the API Gateway console at https://us-east-1.console.aws.amazon.com/apigateway/main/apis?region=us-east-1, select the created URL shortener API, then select "Stages." Choose the endpoint you want, and find the URL there.

Use your own Domain


After deploying the CloudFormation stack (see the chapter above), the URL shortener will be available at a default CloudFront URL. Below, you will find steps to configure it for use with your own root domain (e.g., example.com) or a subdomain (e.g., link.example.com). The following instructions cover how to add an SSL certificate to enable HTTPS and how to redirect traffic from the (sub)domain to the URL shortener.

If you do not have an SSL certificate for the domain you would like to use with the shortener, you need to request one at AWS Certificate Manager at https://us-east-1.console.aws.amazon.com/acm/home?region=us-east-1#/certificates/request. In this tutorial, we are using the domain "aws3-demo.link"; you should use your own domain. On the Request Certificate page, click on Next.

Enter your domain and the "www" subdomain, then click on Request.

Open your newly created certificate and note the CNAME names and values. If you are using AWS Route 53 for domain management, you can use the Create records in Route 53 feature; otherwise, you will need to manually add these records to your domain.

Once the records are validated, the status will change to Success.

Connect the certificate to the URL Shortener CloudFront distribution by going to CloudFront Distributions at https://us-east-1.console.aws.amazon.com/cloudfront/v4/home?region=us-east-1#/distributions and selecting the distribution.

In the Settings tab, click on Edit.

Under Alternate domain name, enter your domain and its "www" subdomain. Select the created SSL certificate and save the changes.

Once the deployment is complete, the CloudFront distribution will be available at this domain. Copy the distribution domain name for the next step.

In the next step, we need to route the traffic from the domain and the "www" subdomain to the CloudFront distribution. Go to your domain management tool (in this tutorial, we have the domain configured in AWS Route 53). Create a record for the root domain and point it to the CloudFront distribution. Repeat the same for the "www" subdomain.

Finally, we need to update an environment variable in the shortener function to use the new domain. Go to the Lambda management console at https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions and select the UrlShortenFunction function.

Go to Configuration, select Environment variables, and change the DOMAIN_NAME variable to your domain.

API endpoint: Shorten

URL endpoint: https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/shorten


Method: POST


"header": {
  "x-api-key": STRING,
  "Content-Type": "application/json"
}


"body": {
  "longUrl": STRING,
  "customSlug": STRING,
  "expireHours": NUMBER,
  "expireClicks": NUMBER,
  "slugLength": STRING
}



Required

"longUrl": The destination URL to which you want to redirect. The protocol (e.g., http, https) must be included. The maximum supported length is 2000 characters.

 
Optional

"customSlug": Define a custom slug (e.g., "aws3.link/customSlug"). If no custom slug is provided, a random string will be generated as the slug.

 "expireHours": Define the number of hours after which the shortened URL will expire. The value must be between 1 and 8760 (1 year). The default is 0, which means the link does not expire.

"expireClicks": Define the number of clicks after which the shortened URL will expire. The default is 0, which means the link does not expire.

"keySlug": Define the length of the randomly generated slug. The value can be set between 4 and 8 characters. If not specified, the default length is 6 characters.

Response:


"body": {
  "shortUrl": STRING,
  "metadata": {
    "longUrl": STRING,
    "domain": STRING,
    "key": STRING,
    "expiration": DATE,
  }
}

Code Samples

The following code samples demonstrate how to call the /shorten endpoint to shorten a given long URL with an automatic expiration after 24 hours. Replace <API-Gateway-ID>, <region> in the endpoint URL, and <Your-API-Key> with your specific values.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/shorten");
request.Headers.Add("x-api-key", "<Your-API-Key>");
var content = new StringContent("{\n    \"longUrl\": \"https://silverlining.cloud\",\n    \"expireHours\": 24\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
API endpoint: Remove

URL endpoint: https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/remove


Method: POST


"header": {
  "x-api-key": STRING,
  "Content-Type": "application/json"
}


"body": {
  "slug": STRING
}


Required
 
"slug": The slug of the short URL you want to delete (e.g., 'mySlug' for aws3.link/mySlug).


Response:


"body": {
  "message": "Provided key has been removed",
  "metadata": {
    "longUrl": STRING,
    "domain": STRING,
    "key": STRING
  }
}
Code Samples

The following code samples demonstrate how to call the /remove endpoint to remove a given short URL with the slug "NVmvZU". Replace <API-Gateway-ID> and <region> in the endpoint URL, and <Your-API-Key> with your specific values.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/remove");
request.Headers.Add("x-api-key", "<Your-API-Key>");
var content = new StringContent("{\n    \"slug\": \"NVmvZU\"\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
API endpoint: List

URL endpoint: https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/list


Method: POST


"header": {
  "x-api-key": STRING,
  "Content-Type": "application/json"
}
"body": empty

Required 
You must include the API key in the x-api-key header. The body parameters can be left empty.


Response:


"body": {
    "items": [
        {
            
            "longUrl": STRING,
            "timeCreated": DATE,
            "slug": STRING,
            "expiration": NUMBER, // if present
            "timeExpire": DATE, // if present
            "totalClicks": NUMBER, // if present
            "expireClicks": NUMBER // if present
        },
        ...
    ]
}

"longUrl": The redirection location of the URL.

"timeCreated: Date when the shortened URL was created.

"slug": Slug of the shortened URL.

"expiration": If timely expiration was set, this is the timestamp when the URL will expire.

"timeExpire: If timely expiration was set, this is the date when the URL will expire.

"totalClicks": If expiration after clicks was set, this is the number of total clicks so far.

"expireClicks": If expiration after clicks was set, this is the number of clicks after which the URL will expire.

The following code samples demonstrate how to call the /list endpoint to receive a list of all short URLs. Replace <API-Gateway-ID> and <region> in the endpoint URL, and <Your-API-Key> with your specific values.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/list");
request.Headers.Add("x-api-key", "<Your-API-Key>");
var content = new StringContent("", null, "text/plain");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
API endpoint: Track

URL endpoint: https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/track


Method: POST


"header": {
  "x-api-key": STRING,
  "Content-Type": "application/json"
}


"body": {
  "slug": STRING
}

Required 
"slug": The slug of the short URL for which you want to track clicks (e.g., 'mySlug' for aws3.link/mySlug).


Response:


"body": {
  "totalHits": NUMBER,
  "hits": [{
    "date": DATE,
    "time": TIME,
    "ip": STRING,
    "method": STRING,
    "resource": STRING,
    "referrer": STRING,
    "user": {
      "platform": {
        "name": STRING,
        "version": STRING,
      },
      "os": {
        "name": STRING,
      },
      "bot": BOOLEAN,
      "flavour": {
        "name": STRING,
        "version": STRING,
      },
      "browser": {
        "name": STRING,
        "version": STRING
      }
    },
    "rawUserAgent": STRING,
    "timeTaken": FLOAT
  }],
  "metadata": {
    "longUrl": STRING,
    "domain": STRING,
    "key": STRING
  }
}

"totalHits": Number of successfully registered clicks.

"hits: List of actual clicks. Consists of the date and time the URL was clicked, IP address of the click, referring URL, and detailed information about the user's device.

"metadata": Contains the long URL, (custom) domain, and key of the request.

Code Samples

The following code samples demonstrate how to call the /track endpoint to receive a list of clicks for the specified short URL. Replace <API-Gateway-ID> and <region> in the endpoint URL, and <Your-API-Key> with your specific values.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://<API-Gateway-ID>.execute-api.<region>.amazonaws.com/prod/track");
request.Headers.Add("x-api-key", "<Your-API-Key>");
var content = new StringContent("{\n    \"slug\": \"cpFWHG\"\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());

Troubleshooting

"message": "Invalid Input: The request contains incorrectly formatted parameters"

This error message means that the body parameters you have passed are malformed. Please follow the instructions given in the endpoint descriptions. Common issues include forgetting to add a comma (',') after every parameter line or missing a parenthesis somewhere.

"message": "Endpoint request timed out"

You receive this error message when the code execution exceeds the maximum timeout (usually 29 seconds).

Setting Up CNAME or A Record for the Apex of a Domain

When integrating your base domain (e.g., example.com) with our service, you may need to set a CNAME or A record to redirect to a URL at the apex of the domain. This step is not necessary if you only intend to integrate a subdomain (e.g., link.example.com) with our service.

Most domain registries (such as GoDaddy) do not allow setting a URL as the destination for the apex of a domain. However, there are workarounds to address this issue. We recommend using AWS Route 53, a DNS hosting service that allows you to configure the records as required by our setup. It offers a way to keep your domain registered with your current registry while managing the DNS through AWS. For guidance on integrating AWS Route 53 with your domain, please refer to this blog post: https://jryancanty.medium.com/domain-by-godaddy-dns-by-route53-fc7acf2f5580.

Alternatively, you can set up a redirection to our backend for the "www" subdomain and then redirect from the apex domain to the "www" subdomain. This approach can be implemented using a service like http://wwwizer.com.

My URL does not expire immediately. Why?

Expire by Time:

The script that removes URLs based on the set expiration hours runs every 15 minutes. Therefore, the expiration can be delayed by up to 15 minutes. In the EventBridge rule, you can increase or decrease this timeframe.

Expire by Clicks:

Expiration by clicks is connected to the CloudFront log stream, which can be delayed by up to 5 minutes.

How can I cancel my subscription?

To cancel your subscription, follow these steps:

  1. Go to the AWS Marketplace Console at https://aws.amazon.com/marketplace/library. Ensure that you are logged into the account that is subscribed to the product you want to cancel.
  2. Find the product you want to cancel and click on 'Manage.'
  3. Click on 'Actions' and then select 'Cancel subscription.'

For more detailed instructions, visit the AWS Marketplace Buyer Guide at https://docs.aws.amazon.com/marketplace/latest/buyerguide/cancel-subscription.html.