Конфиг NGINX для OpenCart

Добрый день.

Выкладываю свой вариант конфига nginx, для запуска OpenCart.

Тестирование проводил на третьей версии OpenCart, на других версиях не пробовал, тем не менее на других версиях OpenCart должен работать.

Предполагаю, что конфиг не идеален, так как я в этом не крайне силён.

Если найдутся на данном форуме люди, которые помогут его допилить/переписать - будет здорово, это будет полезно сообществу нашего форма

Конфиг выкладываю ниже, а также дополнительно прикрепляю его вложением.

В конфиге включёны:

  1. HTTP2.
  2. Rewrite.
  3. GZIP на 6 уровень
  4. Принудительная переадресация на HTTPS
  5. HSTS
  6. Включён журнал запросов и ошибок
  7. Работает ЧПУ

В конфиге необходимо заменить информацию:

  1. Домен "yourdomain.test" заменяем на свой.
  2. IP адрес сервера "1.1.1.1" заменяем на свой.
  3. Проверить, чтобы директива nginx совпадала с той, что в конфиге "include /etc/nginx/..."
  4. Проверить, чтобы совпадала директива, где находится папка сайта "/var/www/yourusername/data/www;"
  5. Проверить, чтобы корректно был указан путь к *.sock файлам "/var/www/php-fpm/yourusername.sock;"
  6. Почту заменить на свою "[email protected]"

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

Конфиг я использовал в ISP панели, если это будет кому-то интересно.

Всем спасибо.


Код:
server {
    server_name yourdomain.test *.yourdomain.test www.yourdomain.test;
    charset UTF-8;
    disable_symlinks if_not_owner from=$root_path;
    include /etc/nginx/vhosts-includes/*.conf;
    include /etc/nginx/vhosts-resources/yourdomain.test/*.conf;
    access_log /var/www/httpd-logs/yourdomain.test.access.log;
    error_log /var/www/httpd-logs/yourdomain.test.error.log notice;
    ssi on;
    set $root_path /var/www/yourusername/data/www;
    location / {
        location ~ [^/]\.ph(p\d*|tml)$ {
            try_files /does_not_exists @php;
        }  
    }
        set $subdomain yourdomain.test;
    if ($host ~* ^((.*).yourdomain.test)$) {
        set $subdomain $1;
    }
    root $root_path/$subdomain;
    return 301 https://$host:443$request_uri;
    index index.php;
    location @php {
        fastcgi_index index.php;
        fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f [email protected]";
        fastcgi_pass unix:/var/www/php-fpm/yourusername.sock;
        fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
        try_files $uri =404;
        include fastcgi_params;
    }
    gzip on;
    gzip_comp_level 6;
    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;
    listen 1.1.1.1:80;
}
server {
    server_name yourdomain.test *.yourdomain.test www.yourdomain.test;
    ssl_certificate "/var/www/httpd-cert/yourusername/yourdomain.test_le1.crtca";
    ssl_certificate_key "/var/www/httpd-cert/yourusername/yourdomain.test_le1.key";
    ssl_ciphers EECDH:+AES256:-3DES:RSA+AES:!NULL:!RC4;
    ssl_prefer_server_ciphers on;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    add_header Strict-Transport-Security "max-age=31536000;";
    ssl_dhparam /etc/ssl/certs/dhparam4096.pem;
    charset UTF-8;
    index index.php;
    disable_symlinks if_not_owner from=$root_path;
    include /etc/nginx/vhosts-includes/*.conf;
    include /etc/nginx/vhosts-resources/yourdomain.test/*.conf;
    access_log /var/www/httpd-logs/yourdomain.test.access.log;
    error_log /var/www/httpd-logs/yourdomain.test.error.log notice;
    ssi on;
    set $root_path /var/www/yourusername/data/www;
        set $subdomain yourdomain.test;
    if ($host ~* ^((.*).yourdomain.test)$) {
        set $subdomain $1;
    }
    root $root_path/$subdomain;
    autoindex off;
    location / {
        location ~ [^/]\.ph(p\d*|tml)$ {
            try_files /does_not_exists @php;
        }  
    }
    if (!-f $request_filename){
        set $rule_3 1$rule_3;
        }
    if (!-d $request_filename){
        set $rule_3 2$rule_3;
        }
    if ($uri !~ ".*\.(ico|gif|jpg|jpeg|png|js|css)"){
        set $rule_3 3$rule_3;
        }
    if ($rule_3 = "321"){
        rewrite ^/([^?]*) /index.php?_route_=$1 last;
        }
    location ~* ^.+\.(jpg|jpeg|gif|png|svg|svgz|eot|otf|woff|ttf|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {
        expires max;
        etag on;
        log_not_found off;
    }
    location = /sitemap.xml {
        rewrite ^(.*)$ /index.php?route=extension/feed/google_sitemap break;
    }
    location = /googlebase.xml {
        rewrite ^(.*)$ /index.php?route=extension/feed/google_base break;
    }
    location /system {
        rewrite ^/system/storage/(.*) /index.php?route=error/not_found break;
    }
    location ~* (\.(tpl|ini))$ {
        deny all;
    }
    location ~ (?i)((\.tpl|\.ini|\.log|(?<!robots)\.txt)) {
        deny all;
    }
    location @opencart {
        rewrite ^/(.+)$ /index.php?_route_=$1 last;
    }
     location /index.html {
        rewrite ^(.*)$ https://yourdomain.test/ permanent;
    }
    location @php {
        fastcgi_index index.php;
        fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f [email protected]";
        fastcgi_pass unix:/var/www/php-fpm/yourusername.sock;
        fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
        try_files $uri =404;
        include fastcgi_params;
    }
    gzip on;
    gzip_comp_level 6;
    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;
    listen 1.1.1.1:443 ssl http2;
}
 

Вложения

Последнее редактирование:

Grubby

Пользователь
Сколько тут всего :) у меня очень простой, может кому пригодится, чем проще тем лучше.
Код:
server {
    listen 80;
    listen [::]:80;
    # listen [::]:80 default ipv6only=on; ## listen for ipv6

    server_name mydomain.com;

    root /var/www/html/;
    index index.php;

    # Add stdout logging
    error_log /dev/stdout info;
    access_log /dev/stdout;

    # Default server block rules
    include /etc/nginx/global/server/defaults.conf;

    # Add option for x-forward-for (real ip when behind elb)
    real_ip_header X-Forwarded-For;
    set_real_ip_from 172.18.0.2;

    # rewrite /admin$ $scheme://$host$uri/ permanent;

    location / {
        try_files $uri $uri/ @opencart;
    }

    # location /admin {
    #     index index.php;
    # }

    location @opencart {
        rewrite ^/(.+)$ /index.php?_route_=$1 last;
    }

    location ~ \.php$ {
        # Check that the PHP script exists before passing it
        try_files $uri =404;

        # regex to split $uri to $fastcgi_script_name and $fastcgi_path
        fastcgi_split_path_info ^(.+\.php)(/.+)$;

        fastcgi_pass unix:/var/run/php7.3-fpm.sock;
        fastcgi_index index.php;
        
        include /etc/nginx/global/fastcgi-params.conf;
    }
}

# Redirect www to non-www
server {
    listen 80;
    listen [::]:80;
    
    server_name www.mydomain.com;

    return 301 https://mydomain.com$request_uri;
}
Все работает отлично и стабильно. Для получения сертификатов автоматом или elb использую traefik.
 

Grubby

Пользователь
Чуть не в тему, а не у кого нет конфига для Caddy (говорят очень шустрая альтернатива nginx), но очень не хочется лезть и конфиг от nginx туда портировать? Вдруг у кого есть уже.
 
Grubby, да, много всего, можно его подсократить, тем более, что конфиг мой старый, но есть в нём полезные фичи:

1. HTTP2 позволяет делает два запроса на один поток, что ускоряет загрузку страницы
2. GZIP сжимает объём передаваемых данных, если на сервере стоит один сайт -можно ставить 6 уровень сжатия, хотя советуют ставить 4 как баланс между сжатием и нагрузкой на сервер
3. HSTS нужен для защиты домена

Я хоть не сильно вникал, но чуть дальше продвинулся в настройках NGINX. Сейчас использую его как прокси в связке с Apache, мне пока что хватает, для меня это оптимальный вариант.
Научился для ISP менеджера задавать шаблонные настройки, которые применяются ко всем доменам + сделал глобальные настройки для nginx /etc/nginx/nginx.conf
Что-то можешь ещё посоветовать для оптимизации ?


Код:
user  apache;
worker_processes  auto;

error_log  /var/log/nginx/error.log crit;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    multi_accept on;
    accept_mutex off;
}

thread_pool ngxcfuncthreadpool threads=32 max_queue=65536;

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    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;
    sendfile_max_chunk 512k;
    aio threads=ngxcfuncthreadpool;
    tcp_nopush on;
    tcp_nodelay on;

    keepalive_timeout 60;
    keepalive_requests 300;

    reset_timedout_connection on;
    client_body_timeout 30;
    send_timeout 6;
   
    server_tokens off;

    client_body_buffer_size 256k;
    client_max_body_size 256M;
   
    gzip on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/vhosts/*/*.conf;

server {
        server_name localhost;
        aio threads=ngxcfuncthreadpool;
        disable_symlinks if_not_owner;
        listen 80;
        listen [::]:80;
        include /etc/nginx/vhosts-includes/*.conf;
        location @fallback {
        error_log /dev/null crit;
        proxy_pass http://127.0.0.1:8080;
        proxy_redirect http://127.0.0.1:8080 /;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        access_log off ;
        }
    }
}
 

motobrat

Пользователь
Здравствуйте. Помогите пожалуйста с настройкой. Уже голову сломал с интернет-магазином, а точнее с настройками сервера. Сервер VPS, на Beget-е, PHP-FPM. На сервере 4 ядра процессор, 8Гб ОЗУ, 60 Гб NVME...
В магазине почти 100к товаров. Часто сайт просто лежит, когда заходят боты.

Конфигурация сервера Frontend:
Код:
server {
    server_name mysite.ru;
    listen 1.111.111.111:443 ssl  http2 ;

    ssl_certificate "/var/www/httpd-cert/mysite.ru_2023-11-25-13-01_01.crt";
    ssl_certificate_key "/var/www/httpd-cert/mysite.ru_2023-11-25-13-01_01.key";
    add_header Strict-Transport-Security "max-age=31536000" always;

    charset utf-8;

    gzip on;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/css text/xml application/javascript text/plain application/json image/svg+xml image/x-icon;
    gzip_comp_level 7;
set $root_path /var/www/user/data/www/mysite.ru/public_html;

    root $root_path;
    disable_symlinks if_not_owner from=$root_path;

    #autoprotect.conf
    location ~* ^/system/storage/session/ { allow 127.0.0.1; deny all; }
    location ~* ^/system/ { allow 127.0.0.1; deny all; }
    location ~ ^/(index|admin/index|install/index)\.php {
    try_files /does_not_exists @php;
}
    location / {
     
        index index.php index.html;
        try_files $uri $uri/ /index.php?$args;
       
        location ~ ^/(index|admin/index)\.php {
        try_files /does_not_exists @php;
        }

        fastcgi_read_timeout 400;
       
        if (!-e $request_filename){
    rewrite ^/(.+)$ /index.php?_route_=$1 last;
        }   
    location = /robots.txt {
        allow all;
        }
    location = /export/feed_yandex_yml_86871283423.xml {
        allow all;
    }
    location ~ /\. {
        deny all;
        }
    location ~ ^/system/ {
        deny all;
        }
    location ~* \.(php|log|tpl|txt|twig|xml|ini)$ {
        deny all;
        }
    location = /sitemap.xml {
        allow all;
        rewrite ^(.*)$ /fx-sitemap last;       
        }

    location ~* \/\.ht {         deny all;    }
    location ~* (\.tpl|.twig|\.ini|\.log|(?<!robots)\.txt) {         deny all;     }
    location ~* \/\.git {        deny all;    }
    location ~* \/image.+(\.php) {               deny all;    }
    location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpeg|avi|zip|gz|bz2|rar|swf|ico|7z|doc|docx|map|ogg|otf|pdf|tff|tif|txt|wav|webp|woff|woff2|xls|xlsx|xml)$ {
        try_files $uri $uri/ /index.php?$args;
        expires 365d;
    }
    location = /googlebase.xml {        rewrite ^(.*)$ /index.php?route=extension/feed/google_base last;    }       
    }

    location @php {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass unix:/var/run/mysite.ru.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
     }

    location @fallback {
        fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f [email protected]";
        fastcgi_pass unix:/var/run/mysite.ru.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include /etc/nginx/fastcgi_params;
    }

    include "/etc/nginx/fastpanel2-sites/user/mysite.ru.includes";
    include /etc/nginx/fastpanel2-includes/*.conf;


    error_log /var/www/user/data/logs/mysite.ru-frontend.error.log;
    access_log /var/www/user/data/logs/mysite.ru-frontend.access.log;
}


server {
     server_name mysite.ru;

    listen 1.111.111.111:80;
    return 301 https://$host$request_uri;

    error_log /var/www/user/data/logs/mysite.ru-frontend.error.log;
    access_log /var/www/user/data/logs/mysite.ru-frontend.access.log;
}


server {
    server_name www.mysite.ru  ;
    listen 1.111.111.111:80;
    listen 1.111.111.111:443 ssl http2 ;

    ssl_certificate "/var/www/httpd-cert/mysite.ru_2023-11-25-13-01_01.crt";
    ssl_certificate_key "/var/www/httpd-cert/mysite.ru_2023-11-25-13-01_01.key";

    add_header Strict-Transport-Security "max-age=31536000" always;
    return 301 $scheme://mysite.ru$request_uri;

    error_log /var/www/user/data/logs/mysite.ru-frontend.error.log;
    access_log /var/www/user/data/logs/mysite.ru-frontend.access.log;
}
Конфигурация Backend:
Код:
[mysite.ru]
user = user
group = user
listen = /var/run/mysite.ru.sock
listen.owner = user
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 200
pm.start_servers = 5
pm.min_spare_servers = 1
pm.max_spare_servers = 15
pm.max_requests      = 500
request_terminate_timeout = 60s
pm.process_idle_timeout = 10s

php_admin_value[date.timezone] = "Europe/Moscow"
php_admin_value[display_errors] = "off"
php_admin_value[log_errors] = "On"
php_admin_value[mail.add_x_header] = "On"
php_admin_value[max_execution_time] = "360"
php_admin_value[max_input_vars] = "10000"
php_admin_value[memory_limit] = "512M"
php_admin_value[mysqlnd.net_cmd_buffer_size] = "8192"
php_admin_value[opcache.blacklist_filename] = "/opt/opcache-blacklists/opcache-*.blacklist"
php_admin_value[opcache.max_accelerated_files] = "100000"
php_admin_value[output_buffering] = "4096"
php_admin_value[post_max_size] = "100M"
php_admin_value[realpath_cache_size] = "8192"
php_admin_value[sendmail_path] = "/usr/sbin/sendmail -t -i -f '[email protected]'"
php_admin_value[session.save_path] = "/var/www/user/data/tmp"
php_admin_value[short_open_tag] = "On"
php_admin_value[upload_max_filesize] = "100M"
php_admin_value[upload_tmp_dir] = "/var/www/user/data/tmp"


catch_workers_output = no
access.format = "%{REMOTE_ADDR}e - [%t] \"%m %r%Q%q %{SERVER_PROTOCOL}e\" %s %{kilo}M \"%{HTTP_REFERER}e\" \"%{HTTP_USER_AGENT}e\""
access.log = /var/www/user/data/logs/mysite.ru-backend.access.log
Что в конфигурации может быть не так?
 
Сверху