Redirect Netlify Preview URL with Hugo

How to redirect Netlify Deploy Preview URLs to your main production URL using the Hugo static site generator

Previously, I wrote about how to redirect a Netlify Deploy Preview URL to your main production URL.

That method is platform-agnostic, meaning you can use it with any static site. However, it requires you to hard-code some configuration directly in the template, which I don’t like.

Since I manage multiple Hugo websites on Netlify, I wanted a simpler way to control this via a configuration file — without hard-coded values.

So I created a reusable Hugo component that can redirect Netlify preview URLs to the main domain.

Hugo Component for Netlify Preview URL Redirect

The first thing to do is add new params inside your config.toml file.

Here’s how I set it up:

[params.services]

[params.services.netlify]
isRedirectPreviewUrl = true
projectName = "your_project_name"

Replace projectName with your actual Netlify project name.

The isRedirectPreviewUrl boolean lets you easily turn the redirect on or off whenever you want.

Next, update your Hugo theme template.

You need to place the following snippet before the closing </head> tag:

{{ if $.Site.Params.Services.Netlify.IsRedirectPreviewUrl }}
{{ with $.Site.Params.Services.Netlify.ProjectName }}
<script type="text/javascript">
    (function () {
        const netlifyProjectName = {{ . }};
        const previewDomain = `--${netlifyProjectName}.netlify.app`;
        if (window.location.hostname.endsWith(previewDomain)) {

            const baseUrlStr = {{ $.Site.BaseURL }};
            const baseUrl = new URL(baseUrlStr);
            const targetUrl = new URL(window.location.href);

            targetUrl.hostname = baseUrl.hostname;
            targetUrl.protocol = baseUrl.protocol;

            window.location.href = targetUrl.toString();
        }
    })();
</script>
{{ end }}
{{ end }}

After that:

  • Set the correct projectName.
  • Deploy your site again.

Now, when you open a Netlify Deploy Preview permalink, it will automatically redirect to your main production URL — which is defined by baseURL in your config.toml.

Final Thoughts

If your Hugo websites share the same theme, adding this Netlify preview URL redirection once makes it reusable across all of them.

No more hard-coded domains. Just clean configuration.

As usual, if you have any questions or a better method, leave a comment below.

Thanks for reading, and see you next time!

Cheers!