It worked locally: two hosting bugs every check missed
Why clean URLs break relative links and compressed responses serve R scripts as HTML
The problem
Before the pull request preview, the local verification suite reported success:
- Rendering:
quarto rendergenerated the entire site without a single warning. - Automated link scanning: An offline link checker scanned 1,712 internal links across the rendered HTML files and reported 0 broken links.
- Automated tests: The full
testthattest suite passed cleanly. - Local manual review: We started a local
python3 -m http.serverand typed a post URL with the trailing slash into the browser address bar.
The branch was pushed and the pull request opened. CI deployed the rendered site to a Firebase Hosting preview channel (see Quarto Firebase previews).
Clicking through the preview exposed two hosting bugs.
Bug 1: The trailing slash and the 404 trap
A post card on the blog index (/blog) linked to posts/qc-demo/index.html. After clicking it, the browser address bar showed https://example.web.app/posts/qc-demo.
Near the bottom of the article, clicking the relative View link for a companion R script navigated to:
https://example.web.app/posts/scripts/qc-demo.R
The browser displayed a 404 Not Found error page.
Yet the file had been rendered and published. When requested directly at its full path, the server responded with 200 OK:
https://example.web.app/posts/qc-demo/scripts/qc-demo.R
The bug stemmed from how web hosts implement clean URLs. In firebase.json, we had enabled "cleanUrls": true. When a user requests posts/qc-demo/index.html, Firebase Hosting issues an HTTP 301 Moved Permanently redirect to /posts/qc-demo (without a trailing slash) and serves the page with 200 OK.
Under RFC 3986 (Section 5.2.3, “Merge Paths”), when a browser resolves a relative URL reference that does not begin with a leading slash, it resolves the reference against the directory component of the base URI. When the base URL is https://example.web.app/posts/qc-demo:
- The final path segment (
qc-demo) does not end with a slash, so the browser interprets it as a file name rather than a directory. - The browser strips
qc-demoto determine the base directory, leavinghttps://example.web.app/posts/. - Appending the companion link produces
https://example.web.app/posts/scripts/qc-demo.R, which does not exist.
Had the base URL contained a trailing slash (https://example.web.app/posts/qc-demo/), the base directory would have remained https://example.web.app/posts/qc-demo/, resolving the relative link to the correct file.
Inspecting the preview server with curl revealed the exact redirect chain:
# Requesting the index file triggers cleanUrls redirect to the non-slashed URL
curl -sI https://example.web.app/posts/qc-demo/index.html | grep -E "^(HTTP|location)"
# HTTP/2 301
# location: /posts/qc-demo
# The non-slashed URL serves content directly
curl -sI https://example.web.app/posts/qc-demo | grep -E "^(HTTP)"
# HTTP/2 200
# The target file exists under the slug directory
curl -sI https://example.web.app/posts/qc-demo/scripts/qc-demo.R | grep -E "^(HTTP)"
# HTTP/2 200
# But the relative link resolved from the non-slashed base URL hits 404
curl -sI https://example.web.app/posts/scripts/qc-demo.R | grep -E "^(HTTP)"
# HTTP/2 404Why did local checks miss this?
- The offline link checker operates on disk: An offline tool like
lycheeparses_site/posts/qc-demo/index.htmlfrom the file system. Because the file physically resides in_site/posts/qc-demo/, the tool finds the companion file in that directory. An offline scanner does not simulate HTTP redirects. - The local URL kept its slash: Python’s local server served
/posts/qc-demo/without the Firebase redirect, so the browser used the post directory as the base. - Manual review typed the trailing slash: We typed
/posts/qc-demo/into the address bar, masking the redirect from the listing link. - Quarto navigation links did not fail: Quarto site navigation links (such as
../../series/foundations.html) use../to navigate up to the root. Because..cannot ascend above the site root/, those links functioned even from the wrong base path. Only relative child links pointing into the post’s own subdirectory broke.
Bug 2: Compressed responses and single-line R scripts
Opening the valid script URL directly showed the second bug:
https://example.web.app/posts/qc-demo/scripts/qc-demo.R
Instead of displaying formatted R code with newlines and comments, the browser displayed the entire script as a single continuous paragraph of plain text. All indentation and line breaks were collapsed into single spaces.
The browser was rendering the .R file as HTML (text/html), where consecutive whitespace characters are collapsed into a single space per HTML rendering rules.
A plain curl -sI request returned this header:
curl -sI https://example.web.app/posts/qc-demo/scripts/qc-demo.R | grep -i "content-type"
# content-type: text/plain; charset=utf-8The text/plain response looked correct until compression headers were included.
The difference lay in how browsers request content. Modern web browsers automatically send compression request headers: Accept-Encoding: gzip, br. When curl sends those same headers, the server’s response changes:
# Request without compression headers
curl -sI https://example.web.app/posts/qc-demo/scripts/qc-demo.R | grep -i "content-type"
# content-type: text/plain; charset=utf-8
# Request with browser compression headers
curl -sI -H "Accept-Encoding: gzip, br" https://example.web.app/posts/qc-demo/scripts/qc-demo.R | grep -i "content-type"
# content-type: text/html; charset=UTF-8On this deployment, requests with compression headers for .R files and the extensionless Git commit-msg hook returned text/html; charset=UTF-8. By contrast, shell scripts (.sh) returned application/x-sh (prompting a browser download), YAML (.yml) returned text/yaml, and Markdown (.md) returned text/markdown.
We did not find Firebase documentation explaining why compressed responses for unrecognised MIME types default to text/html. We report this strictly as observed production behavior.
The web-repo way
Front-end web engineering teams have long recognized that local file systems and generic development servers do not replicate the routing, caching, and compression behavior of production content delivery networks (CDNs). They guard against hosting defects using five standard practices:
- Ephemeral preview environments: Rather than relying exclusively on local development servers, web teams deploy pull requests to isolated preview channels on the real hosting platform (such as Firebase Hosting preview channels, Netlify Deploy Previews, or Cloudflare Pages branch deployments). The preview exercises the exact edge routing, HTTP caching, and header rewrite rules of production.
- Platform emulators for local testing: The host platform’s emulator can exercise its routing rules locally. For Firebase Hosting,
npx firebase-tools emulators:start --only hosting --project demo-previewuses a demo project ID without a Google Cloud login and lets you check clean URLs, redirects, and custom headers. - Browser-realistic smoke tests: Automated post-deployment checks send realistic browser headers (
Accept-Encoding: gzip, brandAccept: text/html,...) to verify status codes, redirect chains (Location), andContent-Typeheaders. - Explicit configuration over CDN defaults: Web teams do not rely on default MIME type tables for custom file formats or extensionless assets. They declare explicit MIME mappings and security headers (such as
X-Content-Type-Options: nosniff) in their repository configuration files. - Configuration regression tests: Critical routing and header rules in hosting configuration files are asserted in automated unit tests so they cannot be removed accidentally during repository refactoring.
The R way
In the R ecosystem, documentation sites and analysis reports are typically compiled to static HTML directories using Quarto, pkgdown, or R Markdown. Applying web hosting discipline to these sites requires addressing the directory structure, configuring explicit host rules, and adding verification tests.
1. Directory layout and relative links in R sites
Static site generators in R organize content into folders with directory index files:
- Quarto blog articles:
_site/posts/<slug>/index.html - pkgdown documentation:
docs/reference/index.htmlanddocs/articles/index.html
In R engineering documentation, articles often reference downloadable companion files—such as runnable analysis scripts, raw CSV datasets, or validation test scripts—using relative paths (for example, [scripts/hosting-check.R](scripts/hosting-check.R)).
When a host serves a directory index at /posts/<slug> without a trailing slash, a relative child link resolves under /posts/. Check the host’s redirects and the final browser URL for pages with links into their own directories.
2. Fixing the trailing slash in firebase.json
Firebase Hosting provides a global "trailingSlash": true setting that redirects static content URLs to add a trailing slash. We did not test that option. It would change URLs across the site, so it would need site-wide link and browser checks.
Instead of altering the global slash behavior, we configure a targeted 301 redirect rule in firebase.json using RE2 regular expressions:
{
"hosting": {
"public": "_site",
"cleanUrls": true,
"redirects": [
{
"regex": "^/posts/([^/.]+)$",
"destination": "/posts/:1/",
"type": 301
}
]
}
}This rule matches any URL path under /posts/ that contains no subsequent slashes or file extension dots, captures the slug into group :1, and issues an HTTP 301 redirect that appends the trailing slash.
With this rule active, opening an article from the listing involves two redirects, then the page and its companion link:
posts/qc-demo/index.htmltriggers a 301 redirect to/posts/qc-demoviacleanUrls./posts/qc-demotriggers a 301 redirect to/posts/qc-demo/via the regex redirect rule./posts/qc-demo/serves the rendered page with200 OK.- The relative companion link resolves inside the post directory and returns
200 OK.
Root pages (such as /blog) remain unaffected.
3. Fixing MIME types and compression headers
There is no standard media type for R source files. To ensure that R scripts, shell scripts, and extensionless files are delivered as plain text across all compression encodings, we define explicit headers in firebase.json:
{
"hosting": {
"headers": [
{
"source": "**/*.@(R|sh)",
"headers": [
{ "key": "Content-Type", "value": "text/plain; charset=utf-8" },
{ "key": "X-Content-Type-Options", "value": "nosniff" }
]
},
{
"source": "/templates/git-hooks/commit-msg",
"headers": [
{ "key": "Content-Type", "value": "text/plain; charset=utf-8" },
{ "key": "X-Content-Type-Options", "value": "nosniff" }
]
}
]
}
}The X-Content-Type-Options: nosniff header instructs browsers to follow the declared MIME type strictly, preventing browsers from attempting MIME type sniffing on response bodies.
4. Testing like a browser
To catch hosting bugs before release, teams should incorporate browser-like verification into their routine R workflow:
First, test locally using the platform emulator rather than a generic server:
npx firebase-tools emulators:start --only hosting --project demo-previewSecond, follow the real user path: open the listing page, click into an article card, and click a companion script link.
Third, verify HTTP response headers using curl with compression flags enabled:
curl -sI -H "Accept-Encoding: gzip, br" https://example.web.app/posts/qc-demo/scripts/qc-demo.RFourth, write guardrail tests in testthat to ensure that hosting configuration rules cannot be deleted inadvertently:
# Read the hosting configuration committed with the site.
config_text <- paste(readLines("firebase.json"), collapse = "\n")
test_that("hosting configuration retains redirect and header guardrails", {
expect_match(config_text, '"regex": "^/posts/([^/.]+)$"', fixed = TRUE)
expect_match(config_text, '"destination": "/posts/:1/"', fixed = TRUE)
expect_match(config_text, '"source": "**/*.@(R|sh)"', fixed = TRUE)
expect_match(config_text, '"source": "/templates/git-hooks/commit-msg"', fixed = TRUE)
expect_match(config_text, '"value": "text/plain; charset=utf-8"', fixed = TRUE)
})5. Other static hosting platforms
Different static hosting platforms document their own URL and header rules:
- Netlify: With Pretty URLs enabled (the default), Netlify forwards a path such as
/aboutto/about/and rewrites/about.htmlto/about/. Custom headers can be set in_headersornetlify.toml. - Cloudflare Pages: Its serving rules redirect
/about/index.htmlto/about/. Custom static-asset headers can be set in a_headersfile in the build output.
Regardless of which hosting platform you use, verify your URLs with curl -sI -H "Accept-Encoding: gzip, br" <url> before sharing rendered documentation with readers.
Companion code
View hosting-check.R · Download
A standalone verification script that scans rendered site directories for relative link traps in directory index pages and verifies HTTP response headers against browser compression encodings. Written in base R and verified with testthat.
hosting-check.R
# Host verification checks: detects trailing-slash relative link traps
# in rendered sites and verifies HTTP response headers for non-HTML assets.
#
# Run with:
# Rscript hosting-check.R
# Rscript hosting-check.R --site _site
# Rscript hosting-check.R --url https://example.web.app/posts/slug/scripts/demo.R
#' Scan a rendered directory for relative links vulnerable to trailing-slash stripping
#'
#' In static site hosting, directory pages served as `<dir>/index.html` often have
#' the `.html` extension stripped by clean URL rules. If the host serves the page
#' at `/dir` without a trailing slash, RFC 3986 path resolution strips `dir` as a
#' file component and resolves relative links against the parent directory.
#' This function finds all relative child links within directory index pages.
#'
#' @param site_dir Path to the rendered site directory (default "_site").
#' @return A data frame with columns: page, target, resolved_path, exists.
find_relative_directory_links <- function(site_dir = "_site") {
if (!dir.exists(site_dir)) {
return(data.frame(
page = character(),
target = character(),
resolved_path = character(),
exists = logical(),
stringsAsFactors = FALSE
))
}
all_indices <- list.files(
site_dir,
pattern = "^index\\.html$",
recursive = TRUE,
full.names = FALSE
)
# Only inspect index.html files located inside subdirectories
sub_indices <- all_indices[dirname(all_indices) != "."]
if (length(sub_indices) == 0L) {
return(data.frame(
page = character(),
target = character(),
resolved_path = character(),
exists = logical(),
stringsAsFactors = FALSE
))
}
results <- list()
for (sub_index in sub_indices) {
full_index_path <- file.path(site_dir, sub_index)
lines <- readLines(full_index_path, warn = FALSE)
page_dir <- dirname(sub_index)
# Extract href and src attribute values
href_matches <- regmatches(
lines,
gregexpr('(?:href|src)=["\']([^"\']+)["\']', lines, perl = TRUE)
)
targets <- character()
for (m in href_matches) {
if (length(m) > 0L) {
cleaned <- sub('^(?:href|src)=["\']', "", m)
cleaned <- sub('["\']$', "", cleaned)
targets <- c(targets, cleaned)
}
}
targets <- unique(targets)
# Filter out anchors, query-only, root-relative, parent-relative, and URI schemes
is_scheme <- grepl("^[a-zA-Z][a-zA-Z0-9+.-]*:", targets)
is_root_rel <- startsWith(targets, "/")
is_anchor <- startsWith(targets, "#")
is_query <- startsWith(targets, "?")
is_parent_rel <- startsWith(targets, "../")
is_blank <- targets == ""
child_relative <- targets[
!is_scheme &
!is_root_rel &
!is_anchor &
!is_query &
!is_parent_rel &
!is_blank
]
for (target in child_relative) {
# Strip anchor or query string for disk path check
disk_target <- sub("[?#].*$", "", target)
resolved_rel <- file.path(page_dir, disk_target)
target_exists <- file.exists(file.path(site_dir, resolved_rel))
results[[length(results) + 1L]] <- list(
page = sub_index,
target = target,
resolved_path = resolved_rel,
exists = target_exists
)
}
}
if (length(results) == 0L) {
return(data.frame(
page = character(),
target = character(),
resolved_path = character(),
exists = logical(),
stringsAsFactors = FALSE
))
}
do.call(rbind, lapply(results, as.data.frame, stringsAsFactors = FALSE))
}
#' Parse raw HTTP response headers
#'
#' Parses raw header lines returned by curl into structured status and header fields.
#' Correctly handles redirect chains (e.g. 301 followed by 200).
#'
#' @param raw_headers Character vector of header lines, or a single newline-delimited string.
#' @return A list with status_code, protocol, headers (named vector), redirects, and chain.
parse_http_headers <- function(raw_headers) {
if (length(raw_headers) == 1L && grepl("[\r\n]", raw_headers)) {
lines <- strsplit(raw_headers, "\r?\n")[[1]]
} else {
lines <- as.character(raw_headers)
}
lines <- trimws(lines)
lines <- lines[lines != ""]
if (length(lines) == 0L) {
return(list(
status_code = NA_integer_,
protocol = NA_character_,
headers = character(),
redirects = list(),
chain = integer()
))
}
# Identify HTTP status lines (e.g. "HTTP/1.1 301 Moved Permanently" or "HTTP/2 200")
status_indices <- grep("^HTTP/[0-9.]+ +[0-9]{3}", lines)
if (length(status_indices) == 0L) {
return(list(
status_code = NA_integer_,
protocol = NA_character_,
headers = character(),
redirects = list(),
chain = integer()
))
}
responses <- list()
for (i in seq_along(status_indices)) {
start_idx <- status_indices[i]
end_idx <- if (i < length(status_indices)) {
status_indices[i + 1L] - 1L
} else {
length(lines)
}
block_lines <- lines[start_idx:end_idx]
status_line <- block_lines[1]
status_match <- regexec(
"^([A-Za-z0-9/.]+) +([0-9]{3})(?: +(.*))?$",
status_line
)
status_parts <- regmatches(status_line, status_match)[[1]]
proto <- if (length(status_parts) >= 2L) status_parts[2] else NA_character_
code <- if (length(status_parts) >= 3L) {
as.integer(status_parts[3])
} else {
NA_integer_
}
header_lines <- block_lines[-1]
parsed_headers <- character()
for (h_line in header_lines) {
sep_idx <- regexpr(":", h_line, fixed = TRUE)
if (sep_idx > 0L) {
key <- tolower(trimws(substr(h_line, 1L, sep_idx - 1L)))
val <- trimws(substr(h_line, sep_idx + 1L, nchar(h_line)))
parsed_headers[key] <- val
}
}
responses[[length(responses) + 1L]] <- list(
protocol = proto,
status_code = code,
headers = parsed_headers
)
}
final_resp <- responses[[length(responses)]]
chain <- vapply(responses, function(r) r$status_code, integer(1))
redirects <- list()
if (length(responses) > 1L) {
for (j in seq_len(length(responses) - 1L)) {
redirects[[j]] <- list(
status_code = responses[[j]]$status_code,
location = unname(responses[[j]]$headers["location"])
)
}
}
list(
status_code = final_resp$status_code,
protocol = final_resp$protocol,
headers = final_resp$headers,
redirects = redirects,
chain = chain
)
}
#' Check HTTP headers for MIME type misclassifications
#'
#' Flags responses where non-HTML assets (.R, .sh, .yml, extensionless scripts)
#' are served as text/html when compressed or requested with browser headers.
#'
#' @param raw_headers Character vector of header lines or string.
#' @param url_path Optional URL or path to infer expected file type.
#' @return A list with valid (logical), status_code, content_type, content_encoding, nosniff, and issue.
check_content_type <- function(raw_headers, url_path = "") {
parsed <- parse_http_headers(raw_headers)
if (is.na(parsed$status_code)) {
return(list(
valid = FALSE,
status_code = NA_integer_,
content_type = NA_character_,
content_encoding = NA_character_,
nosniff = FALSE,
issue = "Could not parse HTTP response headers"
))
}
ct <- unname(parsed$headers["content-type"])
if (is.na(ct)) {
ct <- "missing"
}
ce <- unname(parsed$headers["content-encoding"])
nosniff_hdr <- unname(parsed$headers["x-content-type-options"])
nosniff <- !is.na(nosniff_hdr) && tolower(nosniff_hdr) == "nosniff"
# Detect non-HTML target from url_path
clean_path <- sub("[?#].*$", "", url_path)
is_non_html <- grepl(
"\\.(r|sh|bash|yml|yaml|json|csv|tsv|txt|md|qmd|rmd)$",
clean_path,
ignore.case = TRUE
) ||
grepl("/commit-msg$", clean_path)
is_served_as_html <- grepl("text/html", ct, ignore.case = TRUE)
issue <- ""
valid <- TRUE
if (is_non_html && is_served_as_html) {
valid <- FALSE
issue <- sprintf(
"Non-HTML asset (%s) was served as '%s'",
basename(clean_path),
ct
)
}
list(
valid = valid,
status_code = parsed$status_code,
content_type = ct,
content_encoding = ce,
nosniff = nosniff,
issue = issue
)
}
# Standalone execution
if (sys.nframe() == 0L) {
args <- commandArgs(trailingOnly = TRUE)
if ("--help" %in% args || "-h" %in% args) {
cat("Usage:\n")
cat(
" Rscript hosting-check.R # Run offline verification demo\n"
)
cat(
" Rscript hosting-check.R --site <dir> # Scan directory index pages for relative links\n"
)
cat(
" Rscript hosting-check.R --url <url> # Inspect HTTP headers for target URL\n"
)
} else if ("--site" %in% args) {
site_idx <- which(args == "--site") + 1L
site_dir <- if (site_idx <= length(args)) args[site_idx] else "_site"
cat("Scanning rendered directory:", site_dir, "\n")
findings <- find_relative_directory_links(site_dir)
if (nrow(findings) == 0L) {
cat("No relative child links found in directory index pages.\n")
} else {
cat(sprintf(
"Found %d relative link(s) vulnerable to trailing slash removal:\n",
nrow(findings)
))
print(findings)
}
} else if ("--url" %in% args) {
url_idx <- which(args == "--url") + 1L
if (url_idx <= length(args)) {
target_url <- args[url_idx]
cat("Inspecting headers for:", target_url, "\n")
curl_args <- c(
"-sI",
"-H",
"Accept-Encoding: gzip, br",
"-H",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"--",
target_url
)
raw_output <- tryCatch(
system2("curl", curl_args, stdout = TRUE, stderr = FALSE),
error = function(e) character()
)
res <- check_content_type(raw_output, url_path = target_url)
cat("Status Code: ", res$status_code, "\n")
cat("Content-Type: ", res$content_type, "\n")
cat(
"Content-Encoding:",
ifelse(is.na(res$content_encoding), "none", res$content_encoding),
"\n"
)
cat("Nosniff: ", ifelse(res$nosniff, "yes", "no"), "\n")
cat("Valid MIME: ", ifelse(res$valid, "PASS", "FAIL"), "\n")
if (nzchar(res$issue)) {
cat("Issue: ", res$issue, "\n")
}
} else {
cat("Error: --url requires a target URL argument.\n")
}
} else {
cat("=======================================================\n")
cat("Running offline hosting-check demonstration\n")
cat("=======================================================\n\n")
cat("Step 1: Header parsing with browser compression headers\n")
sample_compressed_bug <- paste(
"HTTP/2 200",
"content-type: text/html; charset=UTF-8",
"content-encoding: gzip",
sep = "\n"
)
res_bug <- check_content_type(
sample_compressed_bug,
url_path = "scripts/ars-demo.R"
)
cat("Bug reproduction (unconfigured CDN response):\n")
cat(" Asset: scripts/ars-demo.R\n")
cat(" Valid: ", res_bug$valid, "\n")
cat(" Type: ", res_bug$content_type, "\n")
cat(" Issue: ", res_bug$issue, "\n\n")
sample_fixed <- paste(
"HTTP/2 200",
"content-type: text/plain; charset=utf-8",
"content-encoding: gzip",
"x-content-type-options: nosniff",
sep = "\n"
)
res_fixed <- check_content_type(
sample_fixed,
url_path = "scripts/ars-demo.R"
)
cat("Fixed configuration (explicit headers):\n")
cat(" Asset: scripts/ars-demo.R\n")
cat(" Valid: ", res_fixed$valid, "\n")
cat(" Type: ", res_fixed$content_type, "\n")
cat(" Nosniff:", res_fixed$nosniff, "\n")
}
}Sources
Web standards and specifications
- RFC 3986 (Uniform Resource Identifier: Generic Syntax): Section 5.2.3 (“Merge Paths”), T. Berners-Lee, R. Fielding, L. Masinter, January 2005. rfc-editor.org/rfc/rfc3986
- WHATWG URL Standard: Section 4.4, URL parsing and relative reference resolution. url.spec.whatwg.org
- MDN Web Docs:
X-Content-Type-Options. developer.mozilla.org
Hosting documentation
- Firebase Hosting: Full configuration guide (
cleanUrls,trailingSlash,redirects, andheaders). firebase.google.com/docs/hosting/full-config - Netlify: Pretty URLs and trailing slash behavior and custom headers.
- Cloudflare Pages: Serving Pages and custom headers.
R package documentation
- testthat: testthat.r-lib.org
- withr: withr.r-lib.org