blogpost
Nginx and the extra slashes

Written by Bram Neijt on .

While playing around with Nginx I came across a weird fenomenon: if I added slashes to the end of my request path (for example http://bneijt/blog//), I would see the page but all the CSS was broken. Not a good thing.

At first I though that Nginx was doing something wrong and I quickly found the merge_slashes directive and decided to turn it on (even though the default dictated that it already should be on). This didn't fix the problem. I could still make requests to http://bneijt/blog// and even http://bneijt///blog// and see a broken page.

Reading more on merge_slashes, it seems to only work with location matching. People say it also works for PHP and FastCGI, but apparently not for static files.

The real problem is Linux in this case. Linux will allow for multiple slashes in a path to find the file, but the browser and URL handling does not agree here. Nginx, the fast server it is, makes a direct connection via the root directive. My configuration:

server {
    server_name bneijt.nl;
    location / {
        expires 24h;
        root /srv/http/site/bneijt.nl;
    }
}

would turn a request for bneijt.nl/blog/// into /srv/http/site/bneijt.nl/blog/// (which is a valid directory according to Linux) and finds index.html there and serves it. The browser then goes on to make a reference to /css/foundation.css from within the page into bneijt.nl/blog///css/foundation.css. But that file does not exist. Apparantly the browser (both Chromium and Firefox) will consider the double slash a new root (or something to that effect).

To overcome this problem, I decided to add a rewrite rule to permenantly redirect anything with a double slash to a single slash url:

server {
    server_name bneijt.nl;
    location / {
        expires 24h;
        rewrite  ^(.*?)/+/(.*)$  $1/$2 permanent;
        root /srv/http/site/bneijt.nl;

    }
}

After writing this, I went out and looked at some websites using nginx and found that thebiglead.com has the same behavior of redirecting.

Another way to solve this is to add your domain to absolute URLs, then the website would work on the weird URL. Also, places where Nginx is used as a proxy this should not be a problem. And furthermore, most websites use a CDN for their static content, which they refer to using the full url.

If you find a site failing on this, please post a comment on their website telling them how to fix it.

Please note that Google uses cookies to track you on this site.