Агрегация css/js D10

Главные вкладки

Аватар пользователя quattro quattro 19 июня в 22:54

Доброго времени всем!

Планирую обновление своих сайтов до Д10, настроил сервер для тестов, поставил друпал10...
Не работает Агрегация css/js. в режиме nginx+php-frm
Когда включена агрегация, ломает тему.
В режимах Apache или CGI работает.

Почитав про настройки nginx добавил их в конфиг, НЕ помогло.

Администраторы хостинга провели проверку сервера, ответ:

Провели диагностику на Вашем сервере. Системный администратор указал следующие >>>>
2024/06/19 18:36:33 [error] 94563#94563: *163 openat() "/var/www/pafes/data/www/pafes.org/sites/default/files/js/js_8WYjKOAH8p-JjetRE9Kc-dqMsRU2p-FQSwHgignqVu0.js" failed (2: No such file or directory), client: 172.16.12.111,
2024/06/19 19:31:13 [error] 94563#94563: *207 openat() "/var/www/pafes/data/www/pafes.org/sites/default/files/css/css_vkFl-zYB7BAUnvzTyffBMCqbU_WPi2MtVFhF4eq9XGg.css" failed (2: No such file or directory), client: 172.16.12.111

Эти сообщения об ошибках являются записями из журнала ошибок веб-сервера Nginx.
В первом сообщении говорится, что при попытке открыть файл js_8WYjKOAH8p-JjetRE9Kc-dqMsRU2p-FQSwHgignqVu0.js произошла ошибка "No such file or directory" (нет такого файла или каталога).
Аналогично, во втором сообщении говорится, что при попытке открыть файл css_vkFl-zYB7BAUnvzTyffBMCqbU_WPi2MtVFhF4eq9XGg.css произошла та же ошибка.
Запрашиваемые файлы отсутствуют в указанных местоположениях.

Добавил каталоги default/files/js/ и default/files/css/
После попытки включить агрегацию, решил постотреть в них... не появились ли там файлы....
Оказалось что созданных каталогов нет...
Создал каталоги заново, они опять исчезли...
Что это?

Комментарии

Аватар пользователя gun_dose gun_dose 19 июня в 23:40

Очевидно, нужно перечитать тему о настройках nginx. Только нало свежая тема, где будет про Drupal 10, а не 9 или 8.
Ну или скиньте сюда, что именно вы добавили в конфиг. Там вся магия в 96 строчке из этого примера
https://git.drupalcode.org/issue/drupal-2937161/-/blob/2937161-drupal-ng...

Аватар пользователя quattro quattro 20 июня в 1:54

вот шаблон конфига под D10: https://github.com/wodby/nginx/blob/master/templates/presets/drupal10.co...
Но чета не сработало!
Решение похоже, вот в тут:
https://www.drupal.org/forum/support/upgrading-drupal/2023-07-16/upgrade...
Чуть позже разбираться буду... но если может кто более грамотный подсказать, буду признателен!

Аватар пользователя quattro quattro 20 июня в 12:10

В документации написано, что нужно добавить
https://github.com/wodby/nginx/blob/master/README.md#drupal
NGINX_VHOST_PRESET= drupal10
Но нет описания ни где, как правильно его добавить.
Кто нибудь подскажет?

В предлагаемом конфигурационном файле первые 3 строки в двойных фигурных скобках, больше похожи на команды:
{{ $static := (getenv "NGINX_STATIC_EXT_REGEX" "css|cur|js|jpe?g|gif|htc|ico|png|xml|otf|ttf|eot|woff|woff2|svg|mp4|svgz|ogg|ogv|pdf|pptx?|zip|tgz|gz|rar|bz2|doc|xls|exe|tar|mid|midi|wav|bmp|rtf|txt|map|webp") }}

{{ $not_found_regex := (getenv "NGINX_DRUPAL_NOT_FOUND_REGEX" "\\.(engine|md|txt|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\\.php)?|xtmpl|yml|yaml)(~|\\.sw[op]|\\.bak|\\.orig|\\.save)?$|^(\\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template)$|(web\\.config|composer\\.(json|lock)|(package|package-lock)\\.json|yarn\\.lock)$|^#.*#$|\\.php(~|\\.sw[op]|\\.bak|\\.orig|\\.save)$") }}

{{ $files_dir_static := (getenv "NGINX_DRUPAL_FILES_STATIC_EXT_REGEX" "txt") }}

Куда их добавлять? Это команды Докер?

Аватар пользователя gun_dose gun_dose 20 июня в 12:18

Если вы не используете docker 4 drupal, то вам и не надо смотреть пример для docker 4 drupal. Смотрите отдельно конфиг nginx без всяких докеров. Вот по этой ссылке:
https://git.drupalcode.org/issue/drupal-2937161/-/blob/2937161-drupal-ng...

Если коротко, вам надо вот этот фрагмент:

# Passes image style and asset generation to PHP.
    location ~ ^/sites/.*/files/(css|js|styles)/ {
        try_files $uri @rewrite;
    }

Скорее всего у вас есть в конфиге такое:

location ~ ^/sites/.*/files/styles/ {
  try_files $uri @rewrite;
}

И вот это надо заменить на то, что выше. То есть вместо styles написать (css|js|styles).
Это связано с тем, что начиная с Drupal 10.1 агрегированные стили и скрипты больше не генерируются во время сброса кэша, а генерируются непосредственно во время их запроса. Точно так же, как стили картинок.

Аватар пользователя quattro quattro 20 июня в 12:18

Наблюдения показали, что при включении агрегации, Друпал 10 перестает создавать каталоги с файлами:
/files/css/css_ и /files/js/js_
как будто ему нет доступа...
Но если посмотреть исходный код страницы сайта, то эти пути в каталоги к файлам есть
Что ещё может влиять на разрешения записи в таком случае?
Может в .htaccess какие записи нужно сделать?

Аватар пользователя gun_dose gun_dose 20 июня в 12:21

Nginx не использует .htaccess, поэтому можно править там всё, что угодно, эффекта не будет.
Папки друпал не создаёт, потому что Nginx не знает, что запросы к этим папкам надо перенаправлять на Друпал и сразу отдаёт 404, даже не вызывая Друпал. Я выше написал, почему это происходит, и как это чинить.

Аватар пользователя quattro quattro 20 июня в 12:27

quattro wrote: Добавил каталоги default/files/js/ и default/files/css/
После попытки включить агрегацию, решил постотреть в них... не появились ли там файлы....
Оказалось что созданных каталогов нет...
Создал каталоги заново, они опять исчезли...

После создания каталогов, и включения агрегации, по ftp пропытки войти в эти каталоги бесполезны... они есть но не пускает в них.
после отключения агрегации, каталоги удаляются...
Если каталоги заранее не создать, и просто включить агрегацию, то они не появляются.

Аватар пользователя gun_dose gun_dose 20 июня в 13:28

quattro wrote: в логах нет такого

Значит 100% дело в настройках nginx. Если вы его редактируете, и это не помогает, то сперва убедитесь, что редактируете именно тот файл, который нужно.

Аватар пользователя quattro quattro 20 июня в 13:48

Редактирую через интерфей ISPmanager-lite 6

server {
server_name new.pafes.org ;
charset off;
index index.php index.html;
disable_symlinks if_not_owner from=$root_path;
include /etc/nginx/vhosts-includes/*.conf;
include /etc/nginx/vhosts-resources/new.pafes.org/*.conf;
access_log /var/www/httpd-logs/new.pafes.org.access.log;
error_log /var/www/httpd-logs/new.pafes.org.error.log notice;
ssi on;
set $root_path /var/www/pafes/data/www/pafes.org;
root $root_path;
gzip on;
gzip_comp_level 5;
gzip_disable "msie6";
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
location / {
location ~ [^/]\.ph(p\d*|tml)$ {
try_files /does_not_exists @php;
}
location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf|webp|woff|woff2)$ {
expires 24h;
}
try_files $uri $uri/ /index.php?$args;
}
return 301 https://$host:443$request_uri;
listen 213.159.214.85:80;
location @php {
include /etc/nginx/vhosts-resources/new.pafes.org/dynamic/*.conf;
fastcgi_index index.php;
fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f webmaster@new.pafes.org";
fastcgi_pass unix:/var/www/php-fpm/2.sock;
fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
try_files $uri =404;
include fastcgi_params;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}

location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
allow 192.168.0.0/16;
deny all;
}

location ~ \..*/.*\.php$ {
return 403;
}

location ~ ^/sites/.*/private/ {
return 403;
}

# Block access to scripts in site files directory
location ~ ^/sites/[^/]+/files/.*\.php$ {
deny all;
}

# Allow "Well-Known URIs" as per RFC 5785
location ~* ^/.well-known/ {
allow all;
}

# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
return 403;
}
location @rewrite {
# For D7 and above:
# Clean URLs are handled in drupal_environment_initialize().
rewrite ^ /index.php;
}

# Don't allow direct access to PHP files in the vendor directory.
location ~ /vendor/.*\.php$ {
deny all;
return 404;
}

# In Drupal 8, we must also match new paths where the '.php' appears in
# the middle, such as update.php/selection. The rule we use is strict,
# and only allows this pattern with the update.php front controller.
# This allows legacy path aliases in the form of
# blog/index.php/legacy-path to continue to route to Drupal nodes. If
# you do not have any paths like that, then you might prefer to use a
# laxer rule, such as:
# location ~ \.php(/|$) {
# The laxer rule will continue to work if Drupal uses this new URL
# pattern with front controllers other than update.php in a future
# release.
location ~ '\.php$|^/update.php' {
fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
# Security note: If you're running a version of PHP older than the
# latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
# See http://serverfault.com/q/627903/94922 for details.
include fastcgi_params;
# Block httpoxy attacks. See https://httpoxy.org/.
fastcgi_param HTTP_PROXY "";
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param QUERY_STRING $query_string;
fastcgi_intercept_errors on;
# PHP 8 socket location.
fastcgi_pass unix:/var/www/php-fpm/2.sock;

}
location ~ ^/sites/.*/files/(css|js|styles)/ {
try_files $uri @rewrite;
}
}
server {
server_name new.pafes.org ;
ssl_certificate "/var/www/httpd-cert/pafes/new.pafes.org_le1.crtca";
ssl_certificate_key "/var/www/httpd-cert/pafes/new.pafes.org_le1.key";
ssl_ciphers EECDH:+AES256:-3DES:RSA+AES:!NULL:!RC4;
ssl_prefer_server_ciphers on;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=31536000;";
ssl_dhparam /etc/ssl/certs/dhparam4096.pem;
charset off;
index index.php index.html;
disable_symlinks if_not_owner from=$root_path;
include /etc/nginx/vhosts-includes/*.conf;
include /etc/nginx/vhosts-resources/new.pafes.org/*.conf;
access_log /var/www/httpd-logs/new.pafes.org.access.log;
error_log /var/www/httpd-logs/new.pafes.org.error.log notice;
ssi on;
set $root_path /var/www/pafes/data/www/pafes.org;
root $root_path;
gzip on;
gzip_comp_level 5;
gzip_disable "msie6";
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
location / {
location ~ [^/]\.ph(p\d*|tml)$ {
try_files /does_not_exists @php;
}
location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf|webp|woff|woff2)$ {
expires 24h;
}
try_files $uri $uri/ /index.php?$args;
}
listen 213.159.214.85:443 ssl http2;
location @php {
include /etc/nginx/vhosts-resources/new.pafes.org/dynamic/*.conf;
fastcgi_index index.php;
fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f webmaster@new.pafes.org";
fastcgi_pass unix:/var/www/php-fpm/2.sock;
fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
try_files $uri =404;
include fastcgi_params;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}

location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
allow 192.168.0.0/16;
deny all;
}

location ~ \..*/.*\.php$ {
return 403;
}

location ~ ^/sites/.*/private/ {
return 403;
}

# Block access to scripts in site files directory
location ~ ^/sites/[^/]+/files/.*\.php$ {
deny all;
}

# Allow "Well-Known URIs" as per RFC 5785
location ~* ^/.well-known/ {
allow all;
}

# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
return 403;
}

location @rewrite {
# For D7 and above:
# Clean URLs are handled in drupal_environment_initialize().
rewrite ^ /index.php;
}

# Don't allow direct access to PHP files in the vendor directory.
location ~ /vendor/.*\.php$ {
deny all;
return 404;
}

# In Drupal 8, we must also match new paths where the '.php' appears in
# the middle, such as update.php/selection. The rule we use is strict,
# and only allows this pattern with the update.php front controller.
# This allows legacy path aliases in the form of
# blog/index.php/legacy-path to continue to route to Drupal nodes. If
# you do not have any paths like that, then you might prefer to use a
# laxer rule, such as:
# location ~ \.php(/|$) {
# The laxer rule will continue to work if Drupal uses this new URL
# pattern with front controllers other than update.php in a future
# release.
location ~ '\.php$|^/update.php' {
fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
# Security note: If you're running a version of PHP older than the
# latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
# See http://serverfault.com/q/627903/94922 for details.
include fastcgi_params;
# Block httpoxy attacks. See https://httpoxy.org/.
fastcgi_param HTTP_PROXY "";
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param QUERY_STRING $query_string;
fastcgi_intercept_errors on;
# PHP 8 socket location.
fastcgi_pass unix:/var/www/php-fpm/2.sock;

}

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
try_files $uri @rewrite;
expires max;
log_not_found off;
}
location ~ ^/sites/.*/files/(css|js|styles)/ {
try_files $uri @rewrite;
}
}

Аватар пользователя jura12 jura12 20 июня в 16:29

Я имею дело с нагруженным сервисом. И решает там не апач или нгикс а многоуровневая политика. Например рефакторинг крона, отключение лога, настройка mysql, добавление ядер, памяти. Настройка кэширования. Рефакторинг темы. Отключение ненужных или загружающих модулей типа поиск и статистикс. Облегчение ошибок 404 и 403. Кэширование на стороне клиента.

Аватар пользователя quattro quattro 21 июня в 3:36

Задачи у нас разные, ...
Мне нужно несколько серверов потом сделать, понятно мне работающих... с Д 10
А тут вообще дичь какая то...
То ли ISPmanager вредит... толь ещё что.
Но ISPmanager Nginx поставил 1.20.1