Skip to content

Instantly share code, notes, and snippets.

@reitzig
Last active January 9, 2023 11:02
Show Gist options
  • Save reitzig/4e3f10a77d77e2474f20d426a00d2869 to your computer and use it in GitHub Desktop.
Save reitzig/4e3f10a77d77e2474f20d426a00d2869 to your computer and use it in GitHub Desktop.
Minimal nginx Docker image with antora redirects
# snip
urls:
latest_version_segment_strategy: redirect:from
latest_version_segment: latest # your choice, doesn't impact the script below
redirect_facility: nginx
# snip
FROM nginxinc/nginx-unprivileged:alpine
COPY build/site /usr/share/nginx/html/
# Inject the rewrite rules antora generates into the nginx config:
# 1. Add \ to the end of every line (to make the multi-line sed command in 3. work), and
# indent all lines (cosmetics).
# 2. Append another ("escaped") empty line (cosmetics).
# 3. Insert what we got before the final closing brace in the default config file.
# NB: Using % as separator for the replace command because rewrite.conf contains many /
# 4. Clean up
RUN sed -e 's/$/\\/' \
-e 's/^/ /' \
< /usr/share/nginx/html/.etc/nginx/rewrite.conf \
> /tmp/rewrite.conf \
&& echo -e "\\" >> /tmp/rewrite.conf \
&& sed -i -e "s%^}%\n$(cat /tmp/rewrite.conf)}\n%" \
/etc/nginx/conf.d/default.conf \
&& rm -rf /tmp/rewrite.conf
@reitzig
Copy link
Author

reitzig commented Jan 4, 2023

When shipping an antora-generated page with nginx as container image, you may not want to mess with the default nginx configuration, and yet import the redirect rules antora may generate. As they say:

By default, nginx will not know to look for the file in this location. You either need to move it to where nginx can find it or configure nginx to use it at this location.

Unfortunately, the official nginx image does not, at the time of this writing, include facilities to include conf files inside the (default) server block.
Thus, hackery.

Note that I leave /usr/share/nginx/html/.etc in the final image; you may want to add removing that folder to the cleanup step.

@reitzig
Copy link
Author

reitzig commented Jan 4, 2023

⚠️ Depending on the deployment (Kubernetes with Route, in my case), further steps are needed (cf. antora/antora#1035). In some cases, it may be enough to extend the above script; add -r and

-e 's% (/[^ ]*)( redirect)?;% \$scheme://\$http_host\1\2;%'

to the sed command in step 1.

⚠️ WIP. Doesn't quite work yet. While the above fixes hostname or port being changed by proxying/forwarding in Kubernetes, the scheme is still mangled in my case. (Not surprising, actually, since HTTPS is terminated in an outer layer.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment