Размещение нескольких доменов на одном VPS

Использую Vps c установленными на нем nginx + centos + django. На данный момент на нем работает один сайт. Необходимо добавить еще один. Просмотрел много статей, но пока безуспешно.

Файл конфигурации nginx

worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/sites-enabled/*.conf;
    server_names_hash_bucket_size 64;


server {

    listen 443 ssl;

    server_name website1.com www.website1.com;
    
    ssl_certificate /etc/ssl/www.website1.com.crt;
    
    ssl_certificate_key /etc/ssl/www.website1.com.key;
    
    location /static/ {
        root /var/www/website1;
        index index.html index.htm index.php;
    }

    location / {
        root /var/www/website1;
        proxy_pass http://127.0.0.1:8888;
        index index.html index.htm index.php;
        proxy_connect_timeout 300s;
        proxy_read_timeout 300s;
    }
    
    
}





    server {
    
    listen 80;
    
    server_name website1.com www.website1.com;
    return 301 https://$host:443$request_uri;
    
    
    location = /favicon.ico {
    alias /var/www/website1/static/img/favicon.png;
}


    
    location /static/ {
        root /var/www/website1;
        index index.html index.htm index.php;
    }

    location / {
        root /var/www/website1;
        proxy_pass http://127.0.0.1:8888;
        index index.html index.htm index.php;
        proxy_connect_timeout 300s;
        proxy_read_timeout 300s;
    }
    }
    
    
    
    
    server {

    listen 443 ssl;

    server_name website2.com www.website2.com;
    
    ssl_certificate /etc/ssl/www.website2.com.crt;
    
    ssl_certificate_key /etc/ssl/www.website2.com.key;
    
    location /static/ {
        root /var/www/website2;
        index index.html index.htm index.php;
    }

    location / {
        root /var/www/website2;
        proxy_pass http://127.0.0.1:8888;
        index index.html index.htm index.php;
        proxy_connect_timeout 300s;
        proxy_read_timeout 300s;
    }
    
    
}





    server {
    
    listen 80;
    
    server_name website2.com www.website2.com;
    return 301 https://$host:443$request_uri;
    
    
    location = /favicon.ico {
    alias /var/www/website2/static/img/favicon.png;
}


    
    location /static/ {
        root /var/www/website2;
        index index.html index.htm index.php;
    }

    location / {
        root /var/www/website2;
        proxy_pass http://127.0.0.1:8888;
        index index.html index.htm index.php;
        proxy_connect_timeout 300s;
        proxy_read_timeout 300s;
    }
    }
}

Пытался использовать один общий файл и два для каждого домена, не помогло, оба сайта не открываются.

worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/sites-enabled/*.conf;
    server_names_hash_bucket_size 64;
}

Файл настроек django, для второго сайта почти такой же

Django settings for apartment project.

Generated by 'django-admin startproject' using Django 2.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os


# Logging settings for django projects, works with django 1.5+
# If DEBUG=True, all logs (including django logs) will be
# written to console and to debug_file.
# If DEBUG=False, logs with level INFO or higher will be
# saved to production_file.
# Logging usage:

# import logging
# logger = logging.getLogger(__name__)
# logger.info("Log this message")



# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'website1.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'website1.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'website1', "static")
]

Что я делаю не так? В настоящий момент ощущение, что оба домена обращаются к одному каталогу, хотя в настройки разные.

К сожалению, глазами я не нашел ошибки в конфигах. Но я знаю, что такая система должна работать. Приведу кое-какие советы, возможно, они вам помогут.

Очень простое и понятное объяснение, как настраивать Nginx я нашел здесь. Советую читать несколько раз, как говорят, до полного просветления.

Обратите внимание на команду ln ... на пятом шаге - многие про неё забывают

Я посмотрел Ваши конфиги, мне в глаза бросилась такая разница: у меня есть "главный файл конфигурации" /etc/nginx/nginx.conf, и в нём такая пара строчек:

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

Как я понял, у Вас этому соответсвует строчка

    include /etc/nginx/sites-enabled/*.conf;

и в этом месте должны лежать конфигурации отдельных сайтов. Сразу вопрос: а они имеют расширение *.conf? Вы вообще выносите конфиши отдельных сайтов в отдельные файлы? Спрашиваю потому, что мне это кажется удобным.

Еще - я привожу команды и пути, исходя из того, чтоу меня используется Ubuntu, в Вашей системе команды и пути могут незначительно отличаться.

Также, экспериментируя, не забывайте проверять корректность конфигурации nginx командой

   sudo nginx -c /etc/nginx/nginx.conf -t

и перезапускать процесс nginx командой

    sudo systemctl restart nginx

Перезапускать надо, чтобы nginx подхватил изменений конфигурации.

Я Вам приведу отрывки из моих файлов - конфигов, сравните со своими. У меня - нормально на одном IP работает несколько сайтов.

Файл /etc/nginx/nginx.conf:

    user www-data;
    worker_processes auto;
    pid /run/nginx.pid;
    include /etc/nginx/modules-enabled/*.conf;

    events {
        worker_connections 768;
        # multi_accept on;
    }

    http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
    }

Пара файлов с конфигурациями виртуальных хостов - просто для примера:

Файл /etc/nginx/sites-available/maket1.junecat.ru:

    server {

        root /var/www/maket1.junecat.ru/Po_maketu;

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

        server_name maket1.junecat.ru www.maket1.junecat.ru;

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


        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/maket1.junecat.ru/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/maket1.junecat.ru/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    }

Файл /etc/nginx/sites-available/stat.junecat.ru:

    server {

        root /var/www/rg-html;

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

        server_name stat.junecat.ru www.stat.junecat.ru;

        location / {
              #auth_basic           "Administrator’s Area";
              #auth_basic_user_file /etc/nginx/passwds/.htpasswd;
              proxy_redirect          http://192.168.0.20:8010/  /; #<-- change
              proxy_pass_header       Server;
              proxy_set_header        X-Real-IP $remote_addr;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header        X-Scheme $scheme;
              proxy_set_header        Host $http_host;
              proxy_set_header        X-NginX-Proxy true;
              proxy_connect_timeout   5;
              proxy_read_timeout      240;
              proxy_intercept_errors  on;

              proxy_pass              http://192.168.0.20:8010/;
        }


        listen [::]:443 ssl; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/stat.junecat.ru/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/stat.junecat.ru/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    }

    server {
        if ($host = www.stat.junecat.ru) {
            return 301 https://$host$request_uri;
        } # managed by Certbot


        if ($host = stat.junecat.ru) {
            return 301 https://$host$request_uri;
        } # managed by Certbot


        listen 80;
        listen [::]:80;

        server_name stat.junecat.ru www.stat.junecat.ru;
        return 404; # managed by Certbot
    }

Что здесь видно?

Часть фрагментов файлов вписана certbot'ом - я не такой умный, чтобы такую конфигурацию из головы написать.

Но пара базовых вещей здесь есть:

как поднять статический сайт на основе директории с файлами (первый пример), и как сделать proxy-redirect (второй пример)

Вернуться на верх