Is this good practice for making subdomains

Is this good practice for making subdomains

Я пытаюсь создать поддомены с помощью своего веб-приложения, однако у меня нет большого опыта работы с nginx. Я пытался найти стабильное решение от SF, но, к сожалению, не смог найти ни одного хорошего решения.

Проблема, которую я пытаюсь решить, заключается в создании гибких поддоменов. Например, если у меня есть какой-либо поддомен, dev.example.comон должен соответствовать файловому каталогу /var/www/example.com/www/dev, а любой тип поддомена (кроме WWW) попытается найти каталог и, если он существует, сделать его корневым.

/var/www/example.com/www/{subdomain}

Текущий каталог, который нужно искать? Если он не существует, то корневой каталог по умолчанию будет:

/var/www/example.com/www/

Это sites-enabledфайл конфигурации моего домена.

server {

    server_name     example.com www.example.com;
    root            /var/www/example.com/www;
    index           index.php index.htm index.html;
    error_page      404 /404.html;
    error_page      500 502 503 504  /50x.html;

    access_log      /var/www/example.com/logs/access.log;
    error_log       /var/www/example.com/logs/errors.log;

    error_page 404 /index.php;

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/www$fastcgi_script_name;
        include fastcgi_params;
    }

    location /pma {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/example.com/www/dev/authfile;
    }

    location /dev {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/example.com/www/dev/authfile;
    }

    location ~ /\.ht
    {
        deny all;
    }
}

server {

    server_name     pma.example.com;
    index           index.php;
    root            /var/www/example.com/www/pma;

    access_log      /var/www/example.com/logs/access.log;
    error_log       /var/www/example.com/logs/errors.log;

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/www$fastcgi_script_name;
        include fastcgi_params;
    }

    location / {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/example.com/www/dev/authfile;
    }
}

server {

    server_name     dev.example.com;
    index           index.php;
    root            /var/www/example.com/www/dev;

    access_log      /var/www/example.com/logs/access.log;
    error_log       /var/www/example.com/logs/errors.log;

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/www$fastcgi_script_name;
        include fastcgi_params;
    }

    location / {
        auth_basic            "Website development";
        auth_basic_user_file  /var/www/example.com/www/dev/authfile;

        if ($request_uri ~* ^(/home(/index)?|/index(.php)?)/?$)
        {
            rewrite ^(.*)$ / permanent;
        }

        if ($host ~* ^www\.(.*))
        {
            set $host_without_www $1;
            rewrite ^/(.*)$ $scheme://$host_without_www/$1 permanent;
        }

        if ($request_uri ~* index/?$)
        {
            rewrite ^/(.*)/index/?$ /$1 permanent;
        }

        if (!-d $request_filename)
        {
            rewrite ^/(.+)/$ /$1 permanent;
        }

        if ($request_uri ~* ^/system)
        {
            rewrite ^/(.*)$ /index.php?/$1 last;
            break;
        }

        if (!-e $request_filename)
        {
            rewrite ^/(.*)$ /index.php?/$1 last;
            break;
        }
    }

    location ~ /\.ht
    {
        deny all;
    }
}

РЕДАКТИРОВАТЬ:Обновленный файл конфигурации:

server {

    #regex capture assigning the subdomain to $subdomain
    server_name ~^(?<subdomain>.+)\.example\.com$;

    if ($host ~* ^www\.(.*)) {
        set $remove_www $1;
        rewrite ^(.*)$ http://$remove_www$1 permanent;
    }

    #if the directory doesn't exist, redirect to the main site
    if (!-d /var/www/example.com/www/$subdomain) {
        rewrite . example.com redirect;
    }

    #if we have made it here, set the root to the above directory
    root /var/www/example.com/www/$subdomain;

    #the rest of your config
    index           index.php;
    access_log      /var/www/example.com/logs/access.log;
    error_log       /var/www/example.com/logs/errors.log;

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/example.com/$subdomain$fastcgi_script_name;
        include fastcgi_params;
    }

    # this needs to be enabled for dev.example.com and pma.example.com only
    location / {
        auth_basic            "Authentication Required";
        auth_basic_user_file  /var/www/example.com/$subdomain/authfile;
    }

    location ~ /\.ht{
        deny all;
    }
}

решение1

Если вы ищете автоматические поддомены, основанные на стандартном шаблоне (например, поддомен для каждого пользователя), вы можете использовать регулярные выражения в вашей директиве server_name. Этот подход позволит вам назначить часть server_name переменной для использования в другом месте вашей конфигурации (например, для установки пути).

It is generally good practice to put 'real' subdomains above the web root, to better separate the sites (and it has the advantage of preventing access via the main site), and to prevent ambiguity as to whether or not a directory maps to a subdomain or not. For example, consider the following path for the root of your 'dev' subdomain: /var/www/example.com/subdomains/dev/www. This would also let you maintain separate logs for your dev site, e.g. /var/www/example.com/subdomains/dev/logs).

The example below uses your pma subdomain as a template, and keeps the subdomain root under the main site.

server{
    #regex capture assigning the subdomain to $subdomain
    server_name ~^(?<subdomain>.+)\.example\.com$;

    #if the directory doesn't exist, redirect to the main site
    if (!-d /var/www/example.com/www/$subdomain) {
        rewrite . example.com redirect;
    }

    #if we have made it here, set the root to the above directory
    root /var/www/example.com/www/$subdomain;

    #the rest of your config
    index           index.php;
    access_log      /var/www/example.com/logs/access.log;
    error_log       /var/www/example.com/logs/errors.log;

    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /var/www/domain.com/$subdomain$fastcgi_script_name;
        include fastcgi_params;
    }

    location / {
        auth_basic            "Authentication Required";
        auth_basic_user_file  /var/www/example.com/$subdomain/authfile;
    }

    location ~ /\.ht{
        deny all;
    }

}

The above idea only really works if all the subdomains are going to follow the same template. In the configuration you have posted, the pma subdomain and the dev subdomain are substantially different (in that the dev subdomain has many rewrites that the pma one does not). Any subdomains that do not follow the 'template' you are using, will need their own server block and config. It is worth mentioning that in the case of two server blocks being applicable (e.g. one with a static server_name and one with a regex server_name), the static server_name will take precedence.

Связанный контент