Nandan Acharya
Nandan Acharya

Reputation: 970

Static files getting 404 with nginx proxy

I have configured nginx to serve static page as below.

       location /home {
                alias /home/username/files/home;
                try_files $uri /home/index.html;
        }

Only index.html loads on http://example.com/home. All other css, js and image files are getting 404 as request is still going for http://example.com/css/style.css instead of http://example.com/home/css/style.css. Is there any way I can configure /home prefix to all the static file without manually adding to all static files?

Upvotes: 0

Views: 742

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15662

You can try to use variable root depending on HTTP Referer header (although it is a dirty hack):

map $http_referer $root {
    ~example\.com/home/    /home/username/files/home;
    default                <your default root here>;
}

server {
    ...
    root $root;

    location /home {
        root /home/username/files;
        try_files $uri /home/index.html;
    }
}

Note that if any of your web pages under /home/ have a links to the main site, those links won't work correctly because of example.com/home/... HTTP Referer header value.

Why root /home/username/files; instead of alias /home/username/files/home;, you ask? Because as nginx documentation states:

When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}

Upvotes: 1

Related Questions