Search code examples
dockernginxreverse-proxyforwardingdirectus

Redirecting problems with dockerized headless cms (directus) + reverse proxy (nginx) using paths/subfolders


I have a dockerized setup with two containers: nginx and backend (=directus). I want nginx to forward request for example.com/api/ to my backend container, which is almost working. The nginx config file looks like this

server {
    listen 80;
    server_name example.com;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /api/ {
        proxy_pass http://backend:8055/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

When I call example.com/api/ I am getting already responses from my backend (=directus), which forwards me to example.com/api/admin. Fine so far, but the referenced script files in the html of the admin page are not loaded. The files are referenced in the html with <script type="module" crossorigin src="./assets/some-script-file.js"></script>. The browser tries to open http://example.com/admin/assets/some-script-file.js instead of http://example.com/api/admin/assets/some-script-file.js. I don't understand why the /api/ part of the url gets lost. How can I fix this?


Solution

  • I solved the problem by using subdomains, so that all relative urls from script scr tags work for that subdomain. Thanks reddit user tschloss for the hint. Note that http://backend:8055/ referes to my backend (=directus) docker container (with container_name "backend" and exposed ports 8055:8055). Also note, that I had to adapt the DNS entries, in ordert to add an A record for api.example.com.

    server {
        listen 80;
        server_name example.com;
    
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
    
    server {
        listen 80;
        server_name api.example.com;
    
        location / {
            proxy_pass http://backend:8055/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }