Как настроить nginx для отображения двух сайтов?

Есть два сайта - site1 и site2, которые лежат в директориях /var/www/site1 и /var/www/site2 соответственно. Необходимо, что бы по запросу http://localhost/ открывался site1, а при запросе http://localhost/site2 открывался site2.

/etc/nginx/sites-available/site1

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name localhost;
    set         $base /var/www/site1;
    root        $base/;

    index index.php index.html index.htm index.nginx-debian.html;


    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:var/run/php/php7.4-fpm.sock;
    }
}

/etc/nginx/sites-available/site2

server {
    listen 80;
    listen [::]:80;
    server_name localhost/site2;
    set         $base /var/www/site2;
    root        $base/;

    index index.php index.html index.htm index.nginx-debian.html;


    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:var/run/php/php7.4-fpm.sock;
    }
}

На данный момент открывается только site1, а при обращении к http://localhost/site2 выдаёт:

404 Not Found nginx/1.18.0 (Ubuntu)

Как настроить nginx так, что бы по запросу http://localhost/ открывался site1, а при запросе http://localhost/site2 открывался site2?


Ответы (2 шт):

Автор решения: Aleksey Vaganov

Т.к. к обоим сайтам вы хотите обращаться по имени хоста localhost, то файл /etc/nginx/sites-available/site2 вам вообще не нужен.

Измените файл /etc/nginx/sites-available/site1

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name localhost;
    root        /var/www;

    index index.php index.html index.htm index.nginx-debian.html;


    location / {
        try_files $uri $uri/ =404;
    }

    location ~ ^/(?!site2) {
        rewrite (.*) /site1$1 last;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:var/run/php/php7.4-fpm.sock;
    }
}
→ Ссылка
Автор решения: IzDmitry

Это для Django, но думаю тоже подойдет.

location / {
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn_site1.sock;
    }


location /site2 {
            proxy_set_header SCRIPT_NAME /site2;
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn_site2.sock;
    }
→ Ссылка