Skip to content

Instantly share code, notes, and snippets.

@carhartl
Created November 16, 2022 08:29
Show Gist options
  • Save carhartl/5dd13a98ce86add2bf4f16b54b13bff4 to your computer and use it in GitHub Desktop.
Save carhartl/5dd13a98ce86add2bf4f16b54b13bff4 to your computer and use it in GitHub Desktop.
Kubernetes nginx-ingress rewriting for SPA
# The rewrite rule for nginx is to pick the first capture group’s match $1 from the path matcher.
#
# In the path matcher regex there are 2 capture groups (the inner groups are not captured):
# /(...)|(.*)
# ^$1 ^$2
#
# So when we match anything that starts with "/api/" or ends with one of "css"/"js"/"png" this will
# populate $1 and nginx passes the url unaltered upstream (-> /$1). If there is no such match, we match
# everything else through the alternation: (.*) to populate $2, but we throw $2 away (we don't make use
# of it in the rewrite target! An empty capture group, in this second scenario $1, will turn into an
# empty string in the rewrite expression, thus "/$1" becomes "/", which is going to load the SPA in
# this case. In the browser the url won’t change and the client-side router takes over.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
ingressClassName: nginx
rules:
- host: example.com
http:
paths:
- path: "/((?:api/.*|.*(?:css|js|png)$))|(.*)"
pathType: Prefix
backend:
service:
name: service
port:
number: 8888
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment