K
K
KirillTrueno2022-04-20 14:09:39
linux
KirillTrueno, 2022-04-20 14:09:39

How to specify root and alias paths in Nginx?

The server has a site root directory, and it has nested static and media subdirectories, which should be opened directly through Nginx.

var
|__ www
    |__ domains
        |__ example.com
            |__ django-app
            |__ static
            |__ media


In the virtual host settings (conf.d), you need to set the paths for static and media.

Option 1: for each location you have to specify root with absolute paths.
server {
    ...
    location /static {
        root /var/www/domains/example.com/static;
    }
    location /media {
        root /var/www/domains/example.com/media;
    }
}


Option 2: the path in the alias is relative (relative to the root path).
server {
    ...
    root /var/www/domains/example.com
    ...
    location /static {
        alias /static;
    }
    location /media {
        alias /media;
    }
}


Which option is correct? Is the alias path relative to root or relative to the linux root?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2022-04-20
@KirillTrueno

Both options are wrong.
In the first option, the request /static/file.pngwill look for a file

/var/www/domains/example.com/static/static/file.png
.
In the second option, the request /static/file.pngwill look for a /static/file.png.
Correct option:
server {
    ...
    root /var/www/domains/example.com;
    ...

    location /static/ {
    }
    location /media/ {
    }
}

PS And it's better to always specify folders in location with a slash at the end. What would not think later why the request /mediaholding/aboutis trying to find the file, and not to be proxied in django.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question