• Как связке апач-nginx настроить переход на https?

    @Hfnas Автор вопроса
    AUser0, спасибо, что не оставили меня.
    я даже отключила весь .htaccess ничего не помогает,
    выполнила команду nginx -t
    Были предупреждения:
    nginx: [warn] conflicting server name "сrm.ru" on 0.0.0.0:80, ignored
    nginx: [warn] conflicting server name "www.crm.ru" on 0.0.0.0:80, ignored


    они исчезли.

    по пути /etc/nginx/sites-available были лишние конфиги crm.conf.save, crm.conf.save1 (хостинг устанавливал платный сертификат, видимо не доделал, а доделывать не хочет). Я их поудалаляла.

    Теперь в папке /etc/nginx/sites-available 3 файла :
    1)crm
    server {
        server_name crm.ru www.crm.ru;
        root /var/www/crm/public_html/public;
    
        location / {
            # try to serve file directly, fallback to index.php
            try_files $uri /index.php$is_args$args;
        }
    
        # optionally disable falling back to PHP script for the asset directories;
        # nginx will return a 404 error when files are not found instead of passing the
        # request to Symfony (improves performance but Symfony's 404 page is not displayed)
        # location /bundles {
        #     try_files $uri =404;
        # }
    
      
        location ~ ^\/build\/ {
            expires 365d;
            add_header Cache-Control "public";
        }
       
    
        location ~ ^/index\.php(/|$) {
            fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
    
            # optionally set the value of the environment variables used in the application
            # fastcgi_param APP_ENV prod;
            # fastcgi_param APP_SECRET <app-secret-id>;
            # fastcgi_param DATABASE_URL "mysql://db_user:db_pass@host:3306/db_name";
    
            # When you are using symlinks to link the document root to the
            # current version of your application, you should pass the real
            # application path instead of the path to the symlink to PHP
            # FPM.
            # Otherwise, PHP's OPcache may not properly detect changes to
            # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
            # for more information).
            # Caveat: When PHP-FPM is hosted on a different machine from nginx
            #         $realpath_root may not resolve as you expect! In this case try using
            #         $document_root instead.
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            fastcgi_param DOCUMENT_ROOT $realpath_root;
            # Prevents URIs that include the front controller. This will 404:
            # http://domain.tld/index.php/some-path
            # Remove the internal directive to allow URIs like this
            internal;
        }
    
        # return 404 for all other php files not matching the front controller
        # this prevents access to other php files you don't want to be accessible.
        location ~ \.php$ {
            return 404;
        }
    
        error_log /var/log/nginx/crm_error.log;
        access_log /var/log/nginx/crm_access.log;
    }

    nano /var/log/nginx/crm_error.log -пустой
    2)crm.conf
    server {
         listen  80;
         return 301 https://$host$request_uri;
    }
    
    
    server {
     listen 443 ssl;
     listen [::]:443 ssl;
     root /var/www/crm/public_html/public;
     server_name crm.ru www.crm.ru;
    ssl_protocols TLSv1.2;
    #ssl on;
    ssl_certificate /etc/nginx/ssl/crm.ru.crt;
    ssl_certificate_key /etc/nginx/ssl/crm.ru.key;
    
    location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    
    location ~ /\.ht {
      deny all;
     }
    }

    как подправила, предупреждения исчезли, но мне не помогло, перенаправления нет

    админка вообще открывается только 'crm.ru/admin/login( то есть , если я наберу https://crm.ru/admin/login перенаправляется на crm.ru/admin/login)

    и ошибка в консоли
    Mixed Content: The page at 'https://сrm.ru/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'crm.ru/admin/login'. This request has been blocked; the content must be served over HTTPS.


    3)default (вообще никакой роли не играет, как мне кажется)
    #
    # This file will automatically load configuration files provided by other
    # applications, such as Drupal or Wordpress. These applications will be made
    # available underneath a path with that package name, such as /drupal8.
    #
    # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
    ##
    
    # Default server configuration
    #
    server {
            listen 80 default_server;
            listen [::]:80 default_server;
    
            # SSL configuration
            #
            # listen 443 ssl default_server;
            # listen [::]:443 ssl default_server;
            #
            # Note: You should disable gzip for SSL traffic.
            # See: https://bugs.debian.org/773332
            #
            # Read up on ssl_ciphers to ensure a secure configuration.
            # See: https://bugs.debian.org/765782
            #
            # Self signed certs generated by the ssl-cert package
            # Don't use them in a production server!
            #
            # include snippets/snakeoil.conf;
    
            root /var/www/html;
    
            # Add index.php to the list if you are using PHP
            index index.html index.htm index.nginx-debian.html;
    
            server_name _;
    
            location / {
                    # First attempt to serve request as file, then
                    # as directory, then fall back to displaying a 404.
                    try_files $uri $uri/ =404;
            }
    
            # pass PHP scripts to FastCGI server
            #
            #location ~ \.php$ {
            #       include snippets/fastcgi-php.conf;
            #
            #       # With php-fpm (or other unix sockets):
            #       fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            #       # With php-cgi (or other tcp sockets):
            #       fastcgi_pass 127.0.0.1:9000;
            #}
    
            # deny access to .htaccess files, if Apache's document root
            # concurs with nginx's one
            #
            #location ~ /\.ht {
            #       deny all;
            #}
    }
    
    
    # Virtual Host configuration for example.com
    #
    # You can move that to a different file under sites-available/ and symlink that
    # to sites-enabled/ to enable it.
    #
    #server {
    #       listen 80;
    #       listen [::]:80;
    #
    #       server_name example.com;
    #
    #       root /var/www/example.com;
    #       index index.html;
    #
    #       location / {
    #               try_files $uri $uri/ =404;
    #       }
    #}


    грешила на кеш сервера, перезагрузила, не помогло.
  • Как связке апач-nginx настроить переход на https?

    @Hfnas Автор вопроса
    AUser0, принощшу извинения, .htaccess дежал в директории еще до моего запроса сюда. . Я выложила конфиг, потому что подумала, может, причина в этом. Поэтому и выложила, что есть.

    Я так поняла .htaccess нкужно убрать. Так как все на nginx завязано , а апач как прокси играет роль.
    Подскажите, хороший материал, который помог в изучении вам этого вопроса, если вам нетрудно. Да, пока я не разбираюсь, не отрицаю.
  • Как связке апач-nginx настроить переход на https?

    @Hfnas Автор вопроса
    # Use the front controller as index file. It serves as a fallback solution when
    # every other rewrite/redirect fails (e.g. in an aliased environment without
    # mod_rewrite). Additionally, this reduces the matching process for the
    # start page (path "/") because otherwise Apache will apply the rewriting rules
    # to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
    DirectoryIndex index.php
    
    # By default, Apache does not evaluate symbolic links if you did not enable this
    # feature in your server configuration. Uncomment the following line if you
    # install assets as symlinks or if you experience problems related to symlinks
    # when compiling LESS/Sass/CoffeScript assets.
    # Options +FollowSymlinks
    
    # Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve
    # to the front controller "/index.php" but be rewritten to "/index.php/index".
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    
    <IfModule mod_rewrite.c>
        Options +FollowSymLinks
        RewriteEngine On
    
        # Determine the RewriteBase automatically and set it as environment variable.
        # If you are using Apache aliases to do mass virtual hosting or installed the
        # project in a subdirectory, the base path will be prepended to allow proper
        # resolution of the index.php file and to redirect to the correct URI. It will
        # work in environments without path prefix as well, providing a safe, one-size
        # fits all solution. But as you do not need it in this case, you can comment
        # the following 2 lines to eliminate the overhead.
        RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$
        RewriteRule .* - [E=BASE:%1]
    
        # Sets the HTTP_AUTHORIZATION header removed by Apache
        RewriteCond %{HTTP:Authorization} .+
        RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]
    
        # Redirect to URI without front controller to prevent duplicate content
        # (with and without `/index.php`). Only do this redirect on the initial
        # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
        # endless redirect loop (request -> rewrite to front controller ->
        # redirect -> request -> ...).
        # So in case you get a "too many redirects" error or you always get redirected
        # to the start page because your Apache does not expose the REDIRECT_STATUS
        # environment variable, you have 2 choices:
        # - disable this feature by commenting the following 2 lines or
        # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
        #   following RewriteCond (best solution)
        RewriteCond %{ENV:REDIRECT_STATUS} =""
        RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
    
        # If the requested filename exists, simply serve it.
        # We only want to let Apache serve files and not directories.
        # Rewrite all other queries to the front controller.
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ %{ENV:BASE}/index.php [L]
    
        Redirect 301 /catalog/utu https://crm.ru/utu
    
    
    #    RewriteEngine On
    #    RewriteCond %{HTTPS} off
    #    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    #    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    </IfModule>
    
    <IfModule !mod_rewrite.c>
        <IfModule mod_alias.c>
            # When mod_rewrite is not available, we instruct a temporary redirect of
            # the start page to the front controller explicitly so that the website
            # and the generated links can still be used.
            RedirectMatch 307 ^/$ /index.php/
            # RedirectTemp cannot be used instead
        </IfModule>
    </IfModule>

    .htaccess /var/www/crm/public_html/public
  • Как связке апач-nginx настроить переход на https?

    @Hfnas Автор вопроса
    AUser0, обновила конфиг, все равно редиректа не происходит-( Благодарю за помощь!
    1)если я в браузере напишу http:/crm.ru, нет перенаправления на https:/crm.ru ....
    2)да, если нажму форму авторизации в админке, или админ перенаправ
    админка вообще открывается только 'crm.ru/admin/login( то есть , если я наберу https://crm.ru/admin/login перенаправляется на crm.ru/admin/login)
  • Как связке апач-nginx настроить переход на https?

    @Hfnas Автор вопроса
    AUser0, ky0, В итоге настроено, как в доках симфони, да DocumentRoot у меня не прописан.... По https есть, сертификат отображается по decoder.link
    <VirtualHost 127.0.0.1:8080>
        ServerName crm.ru
        ServerAlias www.crm.ru
        ServerAdmin we@gmail.com
        DocumentRoot /var/www/crm/public_html/public
        DirectoryIndex index.php
    
        <Directory /var/www/crm/public_html/public>
            AllowOverride None
            Order Allow,Deny
            Allow from All
    
            FallbackResource /index.php
    
        </Directory>
    
         <Directory /var/www/crm/public_html/public/bundles>
            DirectoryIndex disabled
            FallbackResource disabled
        </Directory>
    
        ErrorLog /var/www/crm/error.log
        CustomLog /var/www/crm/access.log combined
    </VirtualHost>

    server {
         listen  80;
         server_name crm.ru www.crm.ru;
         return 301 https://$host$request_uri;
    }
    
    server {
    listen 443;
    listen [::]:443 ssl;
    root /var/www/crm/public_html/public;
    server_name crm.ru www.crm.ru;
    ssl_protocols TLSv1.2;
    ssl on;
    ssl_certificate /etc/nginx/ssl/crm.ru.crt;
    ssl_certificate_key /etc/nginx/ssl/crm.ru.key;
    
    location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    }


    ошибка в консоли браузера:
    Mixed Content: The page at 'https://crm.ru/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://crm.ru/admin/login'. This request has been blocked; the content must be served over HTTPS.


    И в результате , не добавляется в корзину по vue. Так как идет запрос в админку по апи платформ.
    Даже никакой редирект не срабатывает , если я в браузере напишу http:/crm.ru не перенаправления на https:/crm.ru , а админка вообще открывается только 'crm.ru/admin/login( то есть , если я наберу https://crm.ru/admin/login перенаправляется на crm.ru/admin/login)

    Костыль
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />

    не помог.

    https://symfony.com/doc/current/routing.html#routi... тоже не помог...
  • Как связке апач-nginx настроить переход на https?

    @Hfnas Автор вопроса
    AUser0, Апач прослушивает порт 8080 согласно команде netstat -tulpn
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name             
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      32262/nginx: master 
    tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      32019/apache2       
    tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      32262/nginx: master 
    tcp6       0      0 :::80                   :::*                    LISTEN      32262/nginx: master 
    tcp6       0      0 :::443                  :::*                    LISTEN      32262/nginx: master

    поэтому настройки апача такие:

    <VirtualHost 127.0.0.1:8080>
        ServerName crm.ru
        ServerAlias www.crm.ru
        ServerAdmin we@gmail.com
        DocumentRoot /var/www/crm/public_html
        DirectoryIndex /index.php
    
        <Directory /var/www/crm/public_html>
           AllowOverride None
          # Require all granted
    
            Order Allow,Deny
            Allow from all
    
            FallbackResource /index.php
    
        </Directory>
    
         <Directory /var/www/project/public/bundles>
            DirectoryIndex disabled
            FallbackResource disabled
        </Directory>
    
        ErrorLog /var/www/crm/error.log
        CustomLog /var/www/crm/access.log combined
    </VirtualHost>


    Далее, пробую nginx^

    server {
         listen  80;
         server_name crm.ru www.crm.ru;
         return 301 http://www.$host$request_uri;
    }
    
    
    server {
    listen 443;
    listen [::]:443 ssl;
    root /var/www/crm/public_html;
    server_name crm.ru www.crm.ru;
    ssl_protocols TLSv1.2;
    ssl on;
    ssl_certificate /etc/nginx/ssl/crm.ru.crt;
    ssl_certificate_key /etc/nginx/ssl/crm.ru.key;
    
    location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    }


    выводит список файлов проекта, почему?
  • Как перенести сайт на VDS?

    @Hfnas Автор вопроса
    Дмитрий, Это и помогло, а то сменила записи А, АААА в домене, не помогало

    а сертификат ssh перенести со старого шаред на vds как?
  • Как перенести сайт на VDS?

    @Hfnas Автор вопроса
    Дмитрий, вроде сменила запись А , как тут, по инструкции тут, но сайт не запускается с новым доменом....
    Сколько ждать надо?

    Ранее я прописывала в hosts <айпи сайта, где новый(vds)> site.ru

    Cайт с новым доменом отображался на моем компе.
  • Почему удаление позиции по api-platform удаляет все позиции заказа?

    @Hfnas Автор вопроса
    там можно смотреть какие события были затронуты,

    tukreb, не увидела.
    Да, причина была в каскадном удалении! Огромная благодарность!
  • Почему удаление позиции по api-platform удаляет все позиции заказа?

    @Hfnas Автор вопроса
    tukreb,
    думала, думала, не понимаю.....
    data	
    App\Entity\Positions {#1299 ▼
      -id: null
    
      -quantity: 29
      -dateUpdated: DateTime @1671037060 {#1313 ▶}
      -session: Proxies\__CG__\App\Entity\Sessions {#1434 …}
      -Order: null
      -Product: Proxies\__CG__\App\Entity\Products {#1474 …}
    }
    id	
    "22"
    previous_data	
    App\Entity\Positions{#48 ▼
      -id: 22
    
      -quantity: 29
      -dateUpdated: DateTime @1671037060 {#1313 ▶}
      -session: Proxies\__CG__\App\Entity\Sessions {#1434 …}
      -Order: null
      -Product: Proxies\__CG__\App\Entity\Products {#1474 …}
    }


    Дебаг показывает, что удаляет правильно именно элемент (роутер api_positions_delete_item), а по факту удаляет все позиции сессии-( как быть...
    грешу на баг апи-платформ, на версии симфони 5.3 работало....
  • Почему не работает patch при отправке пустой коллекции?

    @Hfnas Автор вопроса
    zxf, 200,к сожалению....
    меняется только isBool: true, а коллекцию не обнуляет....-(,
  • Как исправить ошибку "app.js:11 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'dispatch')"?

    @Hfnas Автор вопроса
    /popup/app.js
    import { createApp } from 'vue';
    import App from './App';
    import store from './store'
    
    const popup =createApp(App).use(store).mount('#modal');
    
    window.popup = {};
    window.popup.showModal =
        (banner) =>popup.$store.dispatch('modal/showModal',"data");


    Cпасибо,а почемку тогда
    в одну строчку
    const show=createApp(App).use(store).use(VueNumberFormat, {prefix: '', suffix:  window.staticStore.currency , decimal: '.',  thousand: ' ', precision: 1});
    ,
    не работает, а так работает.... Поэтомув я так и сделала ранее(см мой вопрос)
    import { createApp } from 'vue';
    import App from './App';
    import store from "./store";
    import VueNumberFormat from 'vue-number-format'
    
    const show=createApp(App);
    show.use(store);
    show.use(VueNumberFormat, {prefix: '', suffix:  window.staticStore.currency , decimal: '.',  thousand: ' ', precision: 1});
    show.mount('#app');
  • Как создать сущность с нужными полями через команду или код?

    @Hfnas Автор вопроса
    Класс финальный, его можно скопировать в свое просстранство имен и работаить.
  • Как настроить роутинг в контроллере и твиге?

    @Hfnas Автор вопроса
    BoShurik, все равно перенаправляет на каталог.
  • Как настроить роутинг в контроллере и твиге?

    @Hfnas Автор вопроса
    Hfnas, BoShurik, большое спасибо, спрошу, наверное, нет нельзя. Похоже разный path в twig ничего не даст, раз урлы почты одинаков.
  • Как настроить роутинг в контроллере и твиге?

    @Hfnas Автор вопроса
    sl0, требование сеошника.
  • Как настроить роутинг в контроллере и твиге?

    @Hfnas Автор вопроса
    но мне такой урл нужен, категория/подкатегория, категория/подкатегория.подкатегория/товар..... Искала , может .htaccess решает?
  • Вопросы по теории symfony?

    @Hfnas Автор вопроса
    tukreb, Спасибо, Добрый Человек!!! Вы меня спасли, не знаете как!!! Извините, за долгий ответ, приболела я. Да, причина, в этом. Быстро летает.
  • Вопросы по теории symfony?

    @Hfnas Автор вопроса
    tukreb, Благодарю за внимание,!!!!
    Если у вас правильно описаны сущности, доктрина не тянет все сущности за раз, а только тогда, когда идёт обращение.
    Чтобы "твиг" не делал миллион запросов к бд, пишут ручные запросы, без использования доктрины.

    Теперь поняла. Спасибо ОГРОМНЕЙШЕЕ. Просто удивилась, что в профайлере симфони появились доп запросы, которые я не делала....
    По коду, я могу предположить, что вы можете делать 2440 встакок кода, вместо одной большой.
    А если у вас это вставляется всё же одним запросом, то возможно стоит разбить это допустим пачками по 100-200 строк.
    В общем не понятно как у вас реализовано.

    Да, верно: Делается циклом по 24 записи всего шагов 120- Итого 2440вставок/обновлении (вариант 1 или вариант2)
    Одним запросом заполнить всю таблицу невозможно, так как каждый шаг рассчитывается на основе предыдущего. Буду делать второй вариант, раз он быстрее. Потому, что как иначе, я не знаю. Расчеты на основе предыдущего шага быстрые, проблема была в сохранении сущности, почему именно сохранение сущности тормозит, я не знаю.
    public function setCreate($entityMS)
        {
            $this->entityManager->persist($entityMS);
            $this->entityManager->flush();
        }
    
        public function setSave()
        {
            $this->entityManager->flush();
        }

    когда идёт обращение

    имеется ввиду второй способ, спасибо. Просто не знаю, что такое "обращение".