How to Find and Fix Broken Links Before Publishing a Website
A renamed page or a changed heading can break a link without changing how your website looks. These mistakes are especially easy to introduce during a redesign, a blog migration or a documentation reorganization.
Checking HTTP status codes catches missing pages, but it will not tell you that a section anchor disappeared or a redirect now leads to unrelated content. Use three kinds of evidence: the source reference, the generated page and the response from the deployed website.
1. Identify what is actually broken
| Problem | Example | What to check |
|---|---|---|
| Missing page | /old-products.html | A 404 or 410 response |
| Missing anchor | /docs/#installation | Whether the target ID still exists |
| Incorrect relative path | ../images/logo.png | The URL resolved from the current page |
| Incorrect query encoding | A value containing & | The parameters received by the destination |
| Redirect loop | A redirects to B, then back to A | The complete redirect chain |
| Expired domain | An old external reference | DNS, ownership and destination content |
| Server error | HTTP 500 | Whether the failure is temporary |
| Soft 404 | An error page returning HTTP 200 | The response body, not just its status |
An unexpected login screen can also make a public reference unusable. Treat a successful response as a starting point for review, not proof that the link still serves its purpose.
2. Resolve relative URLs from the right page
For a page at https://example.com/blog/articles/my-article.html, these links have different destinations:
| HTML link | Resolved URL path |
|---|---|
about.html | /blog/articles/about.html |
../about.html | /blog/about.html |
../../about.html | /about.html |
/about.html | /about.html |
#examples | /blog/articles/my-article.html#examples |
JavaScript’s URL constructor makes the resolution explicit:
const base = "https://example.com/blog/articles/my-article.html";
console.log(new URL("../about.html", base).href);
// https://example.com/blog/about.html
console.log(new URL("/about.html", base).href);
// https://example.com/about.html
A trailing slash changes which part of the base URL is treated as a directory:
new URL("contact", "https://example.com/docs").href;
// https://example.com/contact
new URL("contact", "https://example.com/docs/").href;
// https://example.com/docs/contact
In a browser, an HTML base element can change the base used by links; inspect document.baseURI when the result surprises you. Root-relative links such as /about.html start at the origin root, so they can escape an intended deployment subdirectory such as /my-project/.
Test from nested pages and use the production URL structure in your preview. A link that works on the homepage is not enough evidence.
3. Check HTTP responses and redirects with cURL
Start with a HEAD request to see the response headers:
curl -I "https://example.com/about/"
Some servers reject HEAD or handle it differently from GET. Repeat an unexpected result with GET before declaring the link broken. This command follows redirects, discards the downloaded body and prints the final status and URL:
curl -sS -L -o /dev/null \
--max-time 20 \
--max-redirs 10 \
-w "Status: %{http_code}\nFinal URL: %{url_effective}\nRedirects: %{num_redirects}\n" \
"https://example.com/old-page/"
An illustrative result:
Status: 200
Final URL: https://example.com/new-page/
Redirects: 2
The example uses /dev/null in a Unix-like shell. It has time and redirect limits so a slow server or a loop does not leave the check running indefinitely.
| Status | How to interpret it |
|---|---|
| 200 | Check that the expected content is present. |
| 301 or 308 | If the move is permanent, update links to the appropriate final URL. |
| 302 or 307 | Verify that the temporary redirect is intentional. |
| 401 or 403 | Check whether authentication or request blocking is expected. |
| 404 or 410 | Correct, replace or remove the reference. |
| 429 | Slow down and respect the server’s retry guidance. |
| 500-599 | Investigate the server or retry later. |
Without a fail option, cURL can finish successfully even when the HTTP response is 404. Inspect the status separately from connection failures. Our cURL command guide explains request options and quoting; the cURL command builder can prepare a request with the method and headers you need.
4. Follow the link in a browser
Browser testing catches differences caused by JavaScript routing, cookies and the current login session:
- Open developer tools and select the Network panel.
- Enable the option to preserve the log across navigations.
- Click the link and inspect the request URL, status and response headers.
- Read the destination page and check the final address.
Same-document fragment navigation may make no network request. A link opening a new tab may need inspection in that tab. Check the console as well when a script prevents navigation or builds the wrong URL.
The browser Network inspection guide covers the browser-specific controls. Test important public links while signed out too: a working editor session can hide an authentication requirement.
5. Find missing same-page anchors
A fragment such as #installation is handled by the browser and is not sent to the HTTP server. A normal HTTP status check therefore cannot establish whether this target exists:
<a href="#installation">Installation instructions</a>
<h2 id="installation">Installation</h2>
Run this JavaScript in the console of the page you want to review. It reports missing ordinary same-page anchors and flags malformed percent encoding for manual inspection:
(() => {
const current = new URL(window.location.href);
const brokenAnchors = [];
const hasTarget = target =>
document.getElementById(target) ||
Array.from(document.getElementsByName(target))
.some(element => element.tagName === "A");
for (const link of document.querySelectorAll("a[href]")) {
let url;
try {
url = new URL(link.getAttribute("href"), document.baseURI);
} catch {
continue;
}
const samePage = url.origin === current.origin &&
url.pathname === current.pathname &&
url.search === current.search;
if (!samePage || !url.hash) continue;
// Remove the text-fragment directive before decoding the anchor.
const raw = url.hash.slice(1).split(":~:")[0];
if (!raw || hasTarget(raw)) continue;
let target;
try {
target = decodeURIComponent(raw);
} catch {
brokenAnchors.push({
href: link.getAttribute("href"),
issue: "Check malformed fragment encoding manually"
});
continue;
}
if (hasTarget(target) || target.toLowerCase() === "top") continue;
brokenAnchors.push({
text: link.textContent.trim(),
href: link.getAttribute("href"),
missingTarget: target
});
}
console.table(brokenAnchors);
})();
The check resolves links against document.baseURI, compares the origin, path and query with the current page, and looks for both element IDs and legacy named anchors. It checks the literal fragment before its decoded form. Empty fragments and the special top fallback are not missing targets.
The script does not validate text-fragment matches such as #:~:text=example, anchors on other pages, visibility of the target, or application-specific hash routing. Run it after dynamically created content has appeared. Malformed encodings need manual review because browser decoding is more forgiving than decodeURIComponent().
6. Check query encoding and HTML escaping separately
This URL does not express the intended single search value reliably:
https://example.com/search?q=HTML & CSS
The ampersand separates query parameters. Build the query from its original values instead:
const url = new URL("https://example.com/search");
url.searchParams.set("q", "HTML & CSS");
url.searchParams.set("page", "1");
console.log(url.href);
// https://example.com/search?q=HTML+%26+CSS&page=1
A literal plus sign, an ampersand, a percent sign or a nested URL can change the meaning of a hand-built query. Avoid encoding a value twice. The URL encoder, decoder and query editor helps inspect those values; our shareable search and filter URL guide shows how to keep application state in usable URLs.
Embedding the result in HTML introduces a separate escaping step:
<a href="/search?q=HTML%20%26%20CSS&page=1">
Search for HTML and CSS
</a>
Here %26 belongs to the search value, while & represents the separator between parameters in the HTML source. For the broader distinction between text and markup, see HTML Escaping vs Sanitizing.
7. Validate source references and generated files
Fixing a source reference is easier than hunting for its generated HTML later. A deleted documentation chapter may leave references in several other chapters. A hyperlink analyzer for documentation projects can locate those references in the authoring project before publication.
For a static site or a CMS, combine these checks:
- Source validation: detect references to missing pages or content identifiers.
- Build validation: check generated destinations and anchors.
- Deployment validation: verify real responses, redirects and server routing.
Check a small list with Bash
Put one absolute HTTP or HTTPS URL per line in urls.txt:
https://example.com/
https://example.com/about/
https://example.com/contact/
https://example.com/docs/
Then run this Bash script, which reports the final HTTP status separately from transport failures:
#!/usr/bin/env bash
while IFS= read -r url || [[ -n "$url" ]]; do
url=${url%$'\r'}
[[ -z "$url" || "$url" == \#* ]] && continue
if status=$(curl -sS -L -o /dev/null \
--connect-timeout 5 \
--max-time 20 \
--max-redirs 10 \
-w "%{http_code}" \
-- "$url"); then
case "$status" in
2*)
printf "OK %s %s\n" "$status" "$url"
;;
*)
printf "CHECK %s %s\n" "$status" "$url"
;;
esac
else
printf "ERROR %s\n" "$url"
fi
sleep 1
done < urls.txt
This is a manual report: it does not discover links, inspect anchors, detect soft 404s or return a failing CI exit code when it prints CHECK. The one-second delay reduces request frequency but does not replace handling a server’s rate limits. Use a reviewed list of ordinary page URLs; following a link can trigger application behavior.
Check generated HTML with Lychee
Lychee can inspect links in HTML and Markdown. Once it is installed, this example checks local HTML under a public directory from a Unix-like shell:
lychee --offline --root-dir "$(pwd)/public" \
--index-files index.html --include-fragments --no-ignore \
'public/**/*.html'
The root maps /path links to the generated directory, index.html handles directory URLs, and fragment checking is explicit. --no-ignore includes output that Git ignores. Offline mode checks local files only; absolute HTTPS links still need a separate network check or deliberate remapping to local files. See the Lychee command-line reference for your version’s options.
Local file checks cannot reproduce host redirects or JavaScript-created destinations. Check those on a preview deployment. Limit concurrency and retry temporary failures when inspecting external websites; a rate-limited response is not proof that a reference has disappeared.
8. Repair links while preserving old destinations
Update internal links when a page moves, then preserve access for external references and bookmarks with an appropriate redirect. For a permanent move from /products/old-product.html to /products/new-product.html, an Apache mod_alias rule can match the old path exactly:
RedirectMatch 301 "^/products/old-product\.html$" "/products/new-product.html"
The equivalent path match in an Nginx server configuration is:
location = /products/old-product.html {
return 301 /products/new-product.html;
}
These are examples for the respective servers, not configuration for every host. Check query-string behavior separately: Apache’s rule normally preserves the original query, while the Nginx return shown here does not append it. Test the full old URL when parameters matter.
Redirect only to a relevant replacement. A blanket redirect to the homepage makes missing content harder to diagnose and may leave visitors with no useful next step.
Keep stable anchor IDs when renaming headings:
<h2 id="installation">Getting started</h2>
If the new heading needs a new ID, retain the old target separately:
<span id="installation"></span>
<h2 id="getting-started">Getting started</h2>
For an external resource, look for its new official location, choose a relevant replacement or remove the reference and adjust the surrounding text. Do not substitute an unrelated homepage just to make a report green.
9. Make the checks repeatable
Run internal link checks with content builds and review external references on a separate schedule. A broken internal reference can block a release; a temporary external outage may need a retry and editorial review instead.
Paste this Mermaid source into the Mermaid live editor to adapt the workflow:
flowchart TD
A[Update website content] --> B[Generate website]
B --> C[Check internal links and anchors]
C --> D{Broken internal links?}
D -->|Yes| E[Fix content or URL structure]
E --> B
D -->|No| F[Deploy to staging]
F --> G[Check HTTP responses and redirects]
G --> H{Critical issues?}
H -->|Yes| I[Fix deployment configuration]
I --> F
H -->|No| J[Publish website]
J --> K[Schedule external link checks]
Before publishing, check navigation, breadcrumbs, downloads, nested paths, anchors and query parameters. After deployment, test the production origin and old URLs, including filename case, redirects and the status of a deliberately missing page. A correct local file tree does not establish that the host serves it correctly.