NGINX redirect from subdirectory to root with Slim API framework

I want to forward requests to the subdirectory v1 (subdomain.domain.com/v1) to my root in Nginx. Tried this and this answer (and more variations) with no success. I use the Slim API framework.

My nginx config looks like this:

    events { } http {   include /etc/nginx/mime.types;   server {     listen 80;     server_name subdomain.domain.com;     root /var/www/html;     index index.php;     try_files $uri $uri/ /index.php?$query_string;     location /healthcheck {       auth_basic off;       allow all;       return 200;     }     location / {       if (!-f $request_filename) {         rewrite ^(.*)$ /index.php$1 last;       }     }     #location ~ \.php {     # only allow index.php to be proxied to FastCGI process (more secure than all php files!)     location /index.php {       proxy_pass http://127.0.0.1:9000;     }     location location ~ ^/v1/(.*) {       return 301 $scheme://$http_host/$1$is_args$query_string;     }   } } 

My ingress yaml (Kubernetes) looks like this:

apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata:  name: ingress-ENVIRONMENT_NAME_SHORT-NAME_OF_DEPLOYMENT  namespace: NAME_OF_NAMESPACE  annotations:    kubernetes.io/ingress.class: gce    kubernetes.io/ingress.global-static-ip-name: ip-ENVIRONMENT_NAME_SHORT-NAME_OF_DEPLOYMENT    networking.gke.io/managed-certificates: cert-ENVIRONMENT_NAME_SHORT-NAME_OF_DEPLOYMENT    kubernetes.io/ingress.allow-http: "false" spec:   rules:     - host: NAME_OF_DOMAIN       http:         paths:           - path: /v1/*             backend:               serviceName: svc-ENVIRONMENT_NAME_SHORT-NAME_OF_DEPLOYMENT               servicePort: 443 

I only get this thing to run without /v1 (just subdomain.domain.com). Any guidance appreciated.

Add Comment
1 Answer(s)

The best approach I believe is to have the redirect happen at the ingress level or even prior to hitting the ingress. However, GCE ingress doesn’t support HTTP to HTTPS redirects yet, let alone any kind of redirect.

The way you have it, is basically this way: the ingress gets a /v1 request then it goes to Nginx and then it says redirect to / but that redirect request goes back to the ingress which says I don’t know what to do with / request.

Another approach is just to have your backend serve on /v1 or use a two-layered approach which is pretty common. GCE LB (with no ingress controller) ➡️ Nginx ingress (which does the redirect and has a much richer feature set) ➡️ backend.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.