Check HTTP status codes and final redirected URLs

With this script you can get the current status code for any URL, as well as get the final URL in chain of redirects. 🚀

Check out the GIF to see it in action 🎥


How to add the Script to Google Sheets

1. Copy the script below:

function getStatusCode(url) {
    const url_trimmed = url.trim();

    let cache = CacheService.getScriptCache();
    let result = cache.get(url_trimmed);


    if (!result) {

        const options = {
            'muteHttpExceptions': true,
            'followRedirects': false
        };
        const response = UrlFetchApp.fetch(url_trimmed, options);
        const responseCode = response.getResponseCode();


        cache.put(url_trimmed, responseCode, 21600);
        result = responseCode;
    }

    return result;
}

function getRedirects(url) {
    
    const urlKey = url.trim()+"k";
    let cache = CacheService.getScriptCache();
    let result = cache.get(urlKey);


    if (!result) {
        const params = {
            'followRedirects': false,
            'muteHttpExceptions': true
        };
        const res = UrlFetchApp.fetch(url, params);
        const finalURL = res.getHeaders()['Location'];

        cache.put(urlKey, finalURL, 21600);
        
        result = finalURL;
    }

    return result;

}

2. Head over to Google Sheets

Or if you’re really smart, create a new sheet by going to: https://sheets.new

Select Script editor from the Tools menu.

Paste the script and save it.


3. Add the formulae to any cell in your sheet

=getStatusCode(A2)
=getRedirects(A2)

A2 represents any cell, and you can drag the formula down to check status codes and redirects for multiple URLs. To make it quicker, there’s also a cache built into the script, so that the formula won’t refresh with new values for up to 6 hours.


Thanks for stopping by 👋

I’m Andrew Charlton, the Google Sheets nerd behind Keywords in Sheets. 🤓

Questions? Get in touch with me on social or comment below 👇


More Scripts

Submit your response

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