Технические | Заметки https://t-jo.com малого бизнеса Sun, 24 May 2026 22:25:51 +0000 ru-RU hourly 1 https://wordpress.org/?v=7.0 Разворачивание локальной среды разработки OctoberCMS eCommerce на Homestead с PostgreSQL https://t-jo.com/razvorachivanie-lokalnoj-sredy-razrabotki-octobercms-ecommerce-na-homestead-s-postgresql.html https://t-jo.com/razvorachivanie-lokalnoj-sredy-razrabotki-octobercms-ecommerce-na-homestead-s-postgresql.html#respond Sun, 24 May 2026 22:12:37 +0000 https://t-jo.com/?p=5803 Эта памятка описывает пошаговое разворачивание локальной среды разработки для проекта на
OctoberCMS с eCommerce-архитектурой и базой данных
PostgreSQL. Среда запускается на Laravel Homestead,
Vagrant, Parallels, Apache,
PHP 8.2 и PostgreSQL 18.3 через Docker.

Подход подходит для ситуации, когда production-база работает на современной версии PostgreSQL,
а локальная Homestead-среда должна максимально повторять production-окружение.


1. Общая архитектура локальной среды

Используется следующая схема:

Mac / host machine
    ↓
Vagrant + Parallels
    ↓
Homestead Ubuntu VM
    ↓
Apache + PHP 8.2 + OctoberCMS
    ↓
PostgreSQL 18.3 в Docker-контейнере

Homestead используется как основная виртуальная машина для PHP, Apache и проекта.
PostgreSQL запускается отдельно в Docker-контейнере внутри Homestead, чтобы локальная версия
PostgreSQL совпадала с production.

Важно: встроенная версия PostgreSQL в Homestead может отличаться от production.
Если production использует PostgreSQL 18.x, локально лучше поднять такую же версию через Docker.

2. Пример структуры папок на host machine

/Users/username/Projects/Homestead
/Users/username/Projects/octobercms-project
/Users/username/Projects/html
/Users/username/Projects/PostgreSQL/october-postgres18

Внутри Homestead эти папки будут доступны так:

/home/vagrant/octobercms-project
/home/vagrant/html
/home/vagrant/postgresql

3. Пример Homestead.yaml

---
ip: "192.168.11.11"
memory: 2048
cpus: 2
provider: parallels
box: laravel/homestead
version: "14.0.2"
name: october-dev

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: /Users/username/Projects/octobercms-project
      to:  /home/vagrant/octobercms-project

    - map: /Users/username/Projects/html
      to:  /home/vagrant/html

    - map: /Users/username/Projects/PostgreSQL/october-postgres18
      to:  /home/vagrant/postgresql

sites:
    - map: october.local
      to: /home/vagrant/octobercms-project
      php: "8.2"
      type: "apache"
      wildcard: "yes"
      use_wildcard: "yes"

databases:
    - homestead
    - session
    - laravel

features:
    - mysql: true
    - mariadb: false
    - postgresql: true
    - ohmyzsh: true
    - docker: true
    - webdriver: true

services:
    - enabled:
          - "mysql"
          - "postgresql"
Для Mac Apple Silicon используется обычный box laravel/homestead,
а не laravel/homestead-arm.

4. Запуск Homestead

cd /Users/username/Projects/Homestead
vagrant up --provider=parallels

Если менялся Homestead.yaml:

vagrant reload --provision

Войти в виртуальную машину:

vagrant ssh

5. Настройка hosts на host machine

На Mac нужно добавить локальный домен:

sudo nano /etc/hosts

Добавить:

192.168.11.11 october.local

Проверить:

ping october.local

6. Если provision падает из-за Ondrej PHP PPA

Иногда при provision может появиться ошибка:

Repository 'https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy InRelease'
changed its 'Label' value

Фикс внутри Homestead:

sudo apt update --allow-releaseinfo-change

После этого снова запустить provision с host machine:

cd /Users/username/Projects/Homestead
vagrant reload --provision

7. Настройка PHP 8.2

Внутри Homestead:

sudo apt update --allow-releaseinfo-change
sudo apt update

Установить PHP 8.2 и нужные модули:

sudo apt install -y \
php8.2 \
php8.2-cli \
php8.2-fpm \
php8.2-common \
php8.2-mysql \
php8.2-pgsql \
php8.2-xml \
php8.2-curl \
php8.2-mbstring \
php8.2-zip \
php8.2-gd \
php8.2-intl \
php8.2-bcmath \
php8.2-soap \
php8.2-readline \
php8.2-sqlite3

Сделать PHP 8.2 дефолтной версией в консоли:

sudo update-alternatives --set php /usr/bin/php8.2
php -v

Переключить Apache/FPM на PHP 8.2:

sudo a2dismod php8.3 || true
sudo a2dismod php8.1 || true
sudo a2dismod php8.0 || true

sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.2-fpm || true

sudo systemctl restart php8.2-fpm
sudo systemctl restart apache2

8. Composer и зависимости проекта

Внутри проекта:

cd /home/vagrant/octobercms-project
composer install
Важно: для восстановления проекта чаще всего нужно использовать
composer install, а не composer update.
Команда composer update может изменить версии пакетов, удалить плагины
или поменять composer.lock.

Если случайно был выполнен composer update и удалились файлы плагина:

git restore composer.lock plugins/vendor/plugin-name
composer install

Проверить статус Git:

git status

9. PostgreSQL 18.3 через Docker внутри Homestead

Если production использует PostgreSQL 18.x, локальную базу лучше поднять на такой же версии.
Для этого используется Docker-контейнер postgres:18.3.

9.1. Создать live-папку для PostgreSQL внутри Homestead

sudo mkdir -p /var/lib/pg18-october
sudo chown -R 999:999 /var/lib/pg18-october
Live-файлы PostgreSQL не рекомендуется хранить прямо в shared folder между Mac и Homestead.
PostgreSQL требует строгие Linux permissions. На shared folder могут возникать ошибки
вида Permission denied.

9.2. Запустить PostgreSQL 18.3 контейнер

docker run --name pg18-october \
  -e POSTGRES_DB=october_ecommerce \
  -e POSTGRES_USER=october_user \
  -e POSTGRES_PASSWORD='local_database_password' \
  -p 5433:5432 \
  -v /var/lib/pg18-october:/var/lib/postgresql \
  -d postgres:18.3

Проверить контейнер:

docker ps
docker logs pg18-october

В логах должно быть:

database system is ready to accept connections

9.3. Автозапуск контейнера

docker update --restart unless-stopped pg18-october

Проверить:

docker inspect pg18-october --format '{{.HostConfig.RestartPolicy.Name}}'

Ожидаемый результат:

unless-stopped

9.4. Подключение к PostgreSQL

psql -h 127.0.0.1 -p 5433 -U october_user -d october_ecommerce

Проверить версию PostgreSQL:

SHOW server_version;

10. .env для локальной разработки

APP_NAME="October eCommerce"
APP_ENV=local
APP_DEBUG=true
APP_URL=https://october.local
APP_LOCALE=en

CMS_ASSET_MINIFY=true

BACKEND_URI=backend
BACKEND_TURBO_ROUTER=false

CMS_ROUTE_CACHE=false
CMS_ASSET_CACHE=false
CMS_SAFE_MODE=false

LINK_POLICY=detect
DEFAULT_FILE_MASK=775
DEFAULT_FOLDER_MASK=775

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=october_ecommerce
DB_USERNAME=october_user
DB_PASSWORD='local_database_password'

LOG_CHANNEL=single
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync

SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
SESSION_DOMAIN=

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=log
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=no-reply@example.local
MAIL_FROM_NAME="${APP_NAME}"

RECAPTCHA_V3_SITE_KEY_FRONTEND=your_recaptcha_site_key
RECAPTCHA_V3_SECRET_KEY_BACKEND=your_recaptcha_secret_key
RECAPTCHA_V3_MIN_SCORE=0.3
RECAPTCHA_V3_ENABLED=true
Для полноценной локальной разработки не нужно отключать production-функции.
Если приложение использует reCAPTCHA, secure cookies или HTTPS-only логику,
локальную среду нужно поднимать на HTTPS.

11. HTTPS для локального домена

Для backend login, secure cookies, session и reCAPTCHA локальный сайт лучше запускать на HTTPS.

11.1. Включить Apache-модули

sudo a2enmod ssl
sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod proxy_fcgi
sudo a2enmod setenvif
sudo systemctl restart apache2

11.2. Создать self-signed сертификат

sudo mkdir -p /etc/apache2/ssl

sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
  -keyout /etc/apache2/ssl/october.local.key \
  -out /etc/apache2/ssl/october.local.crt \
  -subj "/C=US/ST=Local/L=Local/O=OctoberCMS/OU=Dev/CN=october.local"

11.3. Создать SSL VirtualHost

Файл:

/etc/apache2/sites-available/october.local-ssl.conf

Конфиг:

<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName october.local
        ServerAlias www.october.local

        DocumentRoot /home/vagrant/octobercms-project

        <Directory /home/vagrant/octobercms-project>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>

        SSLEngine on
        SSLCertificateFile /etc/apache2/ssl/october.local.crt
        SSLCertificateKeyFile /etc/apache2/ssl/october.local.key

        <FilesMatch ".+\.ph(ar|p|tml)$">
            SetHandler "proxy:unix:/var/run/php/php8.2-fpm.sock|fcgi://localhost"
        </FilesMatch>

        ErrorLog ${APACHE_LOG_DIR}/october.local-ssl-error.log
        CustomLog ${APACHE_LOG_DIR}/october.local-ssl-access.log combined
    </VirtualHost>
</IfModule>

11.4. Включить SSL-сайт

sudo a2ensite october.local-ssl.conf
sudo apache2ctl configtest
sudo systemctl reload apache2

Если configtest показывает Syntax OK, конфиг принят.

11.5. Проверить HTTPS

curl -k -I https://october.local

Открывать в браузере:

https://october.local
https://october.local/backend

Браузер может показать предупреждение о self-signed сертификате.
Для локальной разработки это нормально.


12. Дамп production PostgreSQL базы

Пример команды для создания дампа production PostgreSQL базы:

PGSSLMODE=require pg_dump \
  -h production-postgresql-host.example.com \
  -p 5432 \
  -U production_user \
  -d production_database \
  -F c \
  -f latest_rds.dump

Файл latest_rds.dump можно положить на host machine:

/Users/username/Projects/PostgreSQL/october-postgres18/latest_rds.dump

Внутри Homestead этот файл будет виден как:

/home/vagrant/postgresql/latest_rds.dump

13. Restore dump через PostgreSQL 18 Docker

Если дамп создан PostgreSQL 18, а системный pg_restore в Homestead старее,
может появиться ошибка:pg_restore: error: unsupported version in file header

В этом случае restore нужно выполнять через Docker image postgres:18.3.

13.1. Пересоздать локальную базу

PGPASSWORD='local_database_password' dropdb \
  -h 127.0.0.1 \
  -p 5433 \
  -U october_user \
  --if-exists \
  october_ecommerce

PGPASSWORD='local_database_password' createdb \
  -h 127.0.0.1 \
  -p 5433 \
  -U october_user \
  october_ecommerce

13.2. Восстановить dump

docker run --rm --network host \
  -e PGPASSWORD='local_database_password' \
  -v /home/vagrant/postgresql:/backup \
  postgres:18.3 \
  pg_restore \
    -h 127.0.0.1 \
    -p 5433 \
    -U october_user \
    -d october_ecommerce \
    /backup/latest_rds.dump

13.3. Проверить таблицы

psql -h 127.0.0.1 -p 5433 -U october_user -d october_ecommerce -c "\dt"

В базе должны появиться таблицы OctoberCMS, например:

backend_users
system_plugin_versions
cms_theme_templates
system_settings
...

14. Очистка кэшей OctoberCMS / Laravel

После изменения .env, восстановления базы, изменения PHP или Composer:

cd /home/vagrant/octobercms-project

php artisan optimize:clear
php artisan cache:clear
php artisan config:clear
php artisan view:clear

rm -rf storage/framework/sessions/*

sudo systemctl restart apache2

15. Проверка Apache

Проверить активные virtual hosts:

sudo apache2ctl -S

Должен быть локальный домен на HTTPS:

*:443 october.local

Проверить статус Apache:

sudo systemctl status apache2

Если Apache не запущен:

sudo systemctl start apache2

Чтобы Apache запускался автоматически:

sudo systemctl enable apache2

16. Если открывается дефолтная страница Apache

Это означает, что не применился virtual host или provision оборвался.

На host machine:

cd /Users/username/Projects/Homestead
vagrant reload --provision

Внутри Homestead:

sudo apache2ctl -S

Если нужно отключить дефолтный сайт:

sudo a2dissite 000-default.conf
sudo systemctl reload apache2

17. Если backend не пускает в админку

Проверить в .env:

APP_URL=https://october.local
BACKEND_URI=backend
SESSION_SECURE_COOKIE=true
RECAPTCHA_V3_ENABLED=true

После правки:

php artisan optimize:clear
php artisan config:clear
php artisan cache:clear
php artisan view:clear
rm -rf storage/framework/sessions/*
sudo systemctl restart apache2

Открывать backend по HTTPS:

https://october.local/backend
Если backend login просто обновляет страницу и не входит в панель,
причина может быть в HTTP/HTTPS, secure cookies, session или reCAPTCHA.
В такой архитектуре локальный backend нужно проверять именно через HTTPS.

18. Если ошибка: backend_users does not exist

Это значит, что приложение подключилось к PostgreSQL, но база пустая
или dump не восстановился.

Проверка:

psql -h 127.0.0.1 -p 5433 -U october_user -d october_ecommerce -c "\dt"

Если таблиц нет, нужно восстановить production dump через Docker PostgreSQL 18.


19. Если ошибка: partial not found

Пример ошибки:

The partial 'site/example-partial' is not found.

Это проблема темы OctoberCMS, а не Apache, PHP или PostgreSQL.

Проверить файл partial:

ls -la /home/vagrant/octobercms-project/themes/your-theme/partials/site/

Если нужного .htm файла нет, его нужно вернуть в тему
или убрать вызов partial из layout/page.


20. Что происходит после vagrant destroy

После vagrant destroy уничтожается вся виртуальная машина.
Пропадают Docker-контейнеры, crontab, системные настройки и live database files
внутри Homestead.

Пропадёт:

/var/lib/pg18-october
Docker containers
Docker images
crontab
systemd-настройки внутри VM

Останется только то, что лежит в shared folders на host machine:

/Users/username/Projects/PostgreSQL/october-postgres18

Поэтому после vagrant destroy нужно заново поднять PostgreSQL Docker-контейнер
и восстановить базу из latest_rds.dump, если требуется.


21. Быстрый чек-лист после запуска Homestead

cd /Users/username/Projects/Homestead
vagrant up
vagrant ssh

Внутри Homestead:

docker ps
sudo systemctl status apache2
php -v
psql -h 127.0.0.1 -p 5433 -U october_user -d october_ecommerce -c "SHOW server_version;"
curl -k -I https://october.local

Открыть в браузере:

https://october.local
https://october.local/backend

22. Главные выводы

  • Для Mac ARM можно использовать laravel/homestead version 14.0.2.
  • Provider для Apple Silicon: parallels.
  • PHP проекта: 8.2.
  • PostgreSQL лучше поднимать той же major-версии, что и production.
  • PostgreSQL 18.3 удобно запускать через Docker внутри Homestead.
  • OctoberCMS подключается к PostgreSQL через 127.0.0.1:5433.
  • Для restore dump от PostgreSQL 18 нужно использовать postgres:18.3 Docker image.
  • Локальный сайт должен работать на https://october.local.
  • Для полноценной разработки не отключать reCAPTCHA и secure-функции, а правильно поднять HTTPS.
  • composer install безопаснее для восстановления проекта, чем composer update.
  • После vagrant destroy всё внутри VM пропадает, кроме shared folders на host machine.
]]>
https://t-jo.com/razvorachivanie-lokalnoj-sredy-razrabotki-octobercms-ecommerce-na-homestead-s-postgresql.html/feed 0
Symfony VS Laravel https://t-jo.com/symfony-vs-laravel.html https://t-jo.com/symfony-vs-laravel.html#respond Sun, 02 Jun 2024 06:06:16 +0000 https://t-jo.com/?p=5762

Laravel vs Symfony Comparison

Framework Features Comparison

Laravel 11 Symfony 7 Description
Artisan Symfony Console Command-line tools for managing the application, running migrations, generating code, etc.
Tinker Symfony REPL (PsySH) Interactive shell for working with the application from the command line.
Eloquent Doctrine ORM ORM (Object-Relational Mapping) for database interaction.
Facade DB Doctrine DBAL Interface for low-level database operations, below the ORM level.
Laravel Mix (uses npx) Webpack Encore Tools for compiling and managing frontend resources such as CSS and JavaScript.
Blade Twig Templating engines for generating HTML on the server side.
Laravel Scout Elasticsearch (via package) Tools for full-text search, integrating with Elasticsearch and other search systems.
Laravel Socialite HWIOAuthBundle Packages for integrating OAuth social authorizations.
Laravel Passport LexikJWTAuthenticationBundle API authentication implementations using tokens.
Laravel Horizon Symfony Messenger Tools for managing job queues and background processes.

Additional Features Comparison

Laravel 11 Symfony 7 Description
Paginate in Eloquent Pagerfanta or KnpPaginator Pagination of data, implemented in ORM or through third-party bundles.
Laravel Fortify (supports 2FA) SchebTwoFactorBundle Solutions for two-factor authentication (2FA) in web applications.
Laravel Sanctum LexikJWTAuthenticationBundle Solutions for API and SPA authentication, providing tokens and handling session states.

Directory Structure Comparison: Laravel vs Symfony

Laravel 11 Symfony 7 Description
/app /src Main application code, including controllers, models, and other classes.
/app/Http /src/Controller Controllers that manage the logic of incoming requests.
/app/Models /src/Entity Models in Laravel, entities in Symfony (used with Doctrine ORM).
/resources/views /templates User interface templates. Laravel uses Blade, Symfony uses Twig.
/resources/js /assets/js JavaScript files. Symfony uses Webpack Encore for managing assets.
/resources/sass /assets/css SASS/SCSS styles for frontend.
/bootstrap /config/bootstrap.php Bootstrap scripts in Laravel. Part of configuration in Symfony.
/config /config Application configuration files.
/database/migrations /migrations Database migrations.
/public /public Public root directory, the web application entry point.
/routes /config/routes Application routing definitions.
/storage /var Storage for log files, cache, and sessions.
/tests /tests Application tests.
/vendor /vendor Third-party libraries and dependencies installed via Composer.
.env .env Environment configuration file managing sensitive data and configurations.
composer.json composer.json Defines PHP dependencies and other Composer parameters.
package.json package.json Defines Node.js dependencies for frontend tools and libraries.
Laravel Command Symfony Command Description
php artisan list php bin/console list Displays all registered commands in the application.
php artisan make:model ModelName php bin/console make:entity EntityName Creates a new model in Laravel and a new entity in Symfony.
php artisan make:controller ControllerName php bin/console make:controller ControllerName Generates a new controller class in both frameworks.
php artisan make:event EventName php bin/console make:event EventName Creates a new event class in both Laravel and Symfony.
php artisan make:listener ListenerName —event=EventName php bin/console make:subscriber EventName Generates an event listener in Laravel and an event subscriber in Symfony.
php artisan migrate php bin/console doctrine:migrations:migrate Executes database migrations in both Laravel and Symfony.
php artisan serve php bin/console server:run Starts a development server for Laravel and Symfony applications.
php artisan route:list php bin/console debug:router Displays routes registered in the application for both frameworks.
php artisan cache:clear php bin/console cache:clear Clears the application cache in both Laravel and Symfony.
php artisan config:cache php bin/console cache:warmup Creates a cache file for faster configuration loading in Laravel and warms up the cache in Symfony.
php artisan queue:work php bin/console messenger:consume Starts the queue worker in Laravel and consumes messages from the message queue in Symfony.
php artisan make:middleware MiddlewareName php bin/console make:middleware MiddlewareName Generates a new middleware class in both Laravel and Symfony.
php artisan make:migration MigrationName php bin/console make:migration Creates a new database migration file in both frameworks.
php artisan db:seed php bin/console doctrine:fixtures:load Seeds the database with records in Laravel and loads data fixtures in Symfony.
php artisan tinker php bin/console psysh Provides an interactive shell for Laravel and Symfony, powered by PsySH.
php artisan optimize php bin/console cache:warmup Optimizes the framework loading in Laravel and preloads cache in Symfony.
php artisan schedule:run php bin/console scheduler:execute Runs the scheduled tasks configured in Laravel and Symfony.
]]>
https://t-jo.com/symfony-vs-laravel.html/feed 0
Managing Roles and Permissions in Laravel 11 with Spatie Permission https://t-jo.com/managing_roles_and_permissions_in_laravel_11_with_spatie_permission.html https://t-jo.com/managing_roles_and_permissions_in_laravel_11_with_spatie_permission.html#respond Fri, 15 Mar 2024 05:47:34 +0000 https://t-jo.com/?p=5743 This guide provides a straightforward approach to setting up and managing roles and permissions in Laravel 11 using the Spatie Permission package.

Step 1: Install Spatie Laravel Permission

Start by installing the package via Composer and publishing its configurations:

composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate

Step 2: Rollback the Last Migration

If needed, you can rollback the last migration with this command:

php artisan migrate:rollback --step=1

Step 3: Re-run Migrations

If tables were deleted or require recreation, run:

php artisan migrate

Step 4: Update the User Model

Ensure the User model uses the HasRoles trait from Spatie:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // Other model methods...
}

Step 5: Create and Run a Seeder for Roles and Permissions

Create a seeder then populate roles and permissions:

php artisan make:seeder RolesAndPermissionsSeeder
php artisan db:seed --class=RolesAndPermissionsSeeder

Here’s what your seeder might look like:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Create roles
        $roleSuperAdmin = Role::create(['name' => 'superadmin']);
        $roleAdmin = Role::create(['name' => 'admin']);
        $roleUser = Role::create(['name' => 'user']);
        // More roles setup...

        // Assign roles to users
        $userOne = User::where('email', 'j@solarneutrino.com')->first();
        if ($userOne) {
            $userOne->assignRole('superadmin');
        }

        $userTwo = User::where('email', 'user@gmail.com')->first();
        if ($userTwo) {
            $userTwo->assignRole('user');
        }
    }
}

Follow these steps to effectively manage roles and permissions in your Laravel 11 application using the Spatie Permission package.

Step 6: Auto-Assign ‘User’ Role on Registration

To automatically assign the «user» role to all newly registered users, you need to modify the registration handling method. This is usually the create method in the RegisterController.

  1. Open the RegisterController.php file, typically located in the app/Http/Controllers/Auth directory.

  2. Add the role assignment in the create method after creating a new user:

    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    
        // Assigning the "user" role
        $user->assignRole('user');
    
        return $user;
    }
    

This code snippet ensures that every new user is automatically granted the «user» role upon registration.

Step 7: Using @role and @hasrole Directives in Blade Templates

To manage content visibility based on user roles within Blade templates, Laravel’s Spatie Permission package provides two useful directives: @role and @hasrole. These directives help in rendering content conditionally based on the user’s roles.

Examples:

<!-- Display content only if the user has the "superadmin" role. Checks for any of the specified roles if multiple are provided. -->
@role('superadmin')
    <p>This text can see user from Superadmin group</p>
@endrole

<!-- Alternative way using @hasrole, strictly checks for the specified role. Used for checking a single role. -->
@hasrole('superadmin')
    <p>This text can see user from Superadmin group</p>
@endhasrole

<!-- Display content only if the user has the "user" role. Checks for any of the specified roles if multiple are provided. -->
@role('user')
    <p>This text can see user from User group</p>
@endrole

<!-- Alternative way using @hasrole, strictly checks for the specified role. Used for checking a single role. -->
@hasrole('user')
    <p>This text can see user from User group</p>
@endhasrole

Explanations:

  • @role: This directive checks if the current authenticated user has one or more specified roles. If multiple roles are passed (separated by commas), it returns true if the user has at least one of them. In the provided examples, only one role is specified, so the behavior is similar to @hasrole.
  • @hasrole: This directive strictly checks if the user has the specified role. It’s ideal for situations where you need to verify the presence of only one specific role. This directive always takes only one role at a time.

These directives are instrumental in controlling what content a user can see based on their roles, enhancing security and user experience by tailoring the UI to meet individual user permissions.

Step 8: Applying Roles to Routes or Route Groups

In Laravel 11, the structure for handling middleware has changed significantly, including the deprecation of the app/Http/Kernel.php file. Middleware can now be applied directly in the routing files such as web.php or api.php. Here’s how to set up and use Spatie Permission Middleware to restrict route access to users with specific roles.

Registering and Applying Middleware

You can register your middleware directly in the routing file. Below is a step-by-step guide on how to apply the Spatie Permission Middleware directly to your routes:

  1. Add the Middleware Namespace:

    At the beginning of your routing file (e.g., routes/web.php), add the namespace for the middleware:

    <?php
    use Spatie\Permission\Middlewares\RoleMiddleware;
    ?>
    
  2. Apply Middleware to a Route:

    Apply the middleware directly to the routes as follows:

    <?php
    use Illuminate\Support\Facades\Route;
    
    Route::middleware(['auth', 'verified', RoleMiddleware::class . ':superadmin'])
        ->get('/contact-messages', function () {
            return view('contact-messages');
        })->name('contact-messages');
    ?>
    

    Note that we pass the RoleMiddleware class with the role parameter (superadmin) directly into the middleware array.

Laravel 10, 9, …

To secure routes based on user roles, Laravel allows the application of middleware to individual routes or groups of routes. Using Spatie’s permission package, you can enforce role-based access controls effectively.

Applying Roles to a Single Route:

use Illuminate\Support\Facades\Route;

// Ensure you have registered the 'role' middleware in your old version Laravel - Kernel.php after Laravel 11 it can be seeder class or another tinker way. 
Route::get('/admin', function () {
    return view('admin.dashboard');
})->middleware('role:admin');

This route is accessible only to users who have the ‘admin’ role. If a user without this role tries to access it, they will be redirected as defined by your middleware handling.

Applying Roles to a Route Group:

use Illuminate\Support\Facades\Route;

Route::middleware(['role:admin'])->group(function () {
    Route::get('/admin/dashboard', function() {
        return view('admin.dashboard');
    });
    Route::get('/admin/settings', function() {
        return view('admin.settings');
    });
});

This group of routes is secured with the ‘admin’ role, ensuring that all routes within this group require a user to be an ‘admin’ to gain access. This method is particularly effective for sectioning parts of your application that should be restricted to users with specific roles.

Note: It’s important to ensure that your Kernel.php file is properly configured to recognize the Spatie middleware. Add the Spatie middleware to your $routeMiddleware array if it’s not already present:

protected $routeMiddleware = [
    // other middleware
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
];

Following these best practices not only enhances the security of your application by ensuring proper role-based access control but also aligns with Spatie’s documentation, ensuring you are implementing features in the recommended manner.

For example:

Utilized Laravel Breeze for authentication with frontend-designed Tailwind CSS and Spatie for role-based access control. Integrated Laravel Sanctum for secure token-based API and Laravel Multidomain middleware for simpler project integration. Enhanced security by hosting the admin panel on a separate domain (admin.solarneutrino.com) and (solarneutrino.com). Implemented a contact form with functionalities for email notifications, logging via Eloquent MySQL, and Telegram alerts. Infrastructure set up on EC2, utilizing Route 53 for DNS management and AWS SES for email dispatch.

]]>
https://t-jo.com/managing_roles_and_permissions_in_laravel_11_with_spatie_permission.html/feed 0
Node.js vs Go vs Laravel: 5 Advantages in Microservices Development https://t-jo.com/node-js_vs_go_vs_laravel_in_microservices.html https://t-jo.com/node-js_vs_go_vs_laravel_in_microservices.html#respond Fri, 05 May 2023 22:28:55 +0000 https://t-jo.com/?p=5728 Microservices architecture has become a go-to strategy for building scalable, maintainable, and flexible applications. When considering this architectural pattern, choosing the right technology stack is crucial. Three popular options are Node.js, Go, and Laravel. This article explores five key advantages each of these technologies offers in microservices development.

Node.js

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It offers several advantages in microservices development:

  • Non-Blocking I/O Model: Node.js excels at handling concurrent requests due to its event-driven, non-blocking I/O model. This makes it ideal for building real-time microservices with high throughput requirements.
  • Vast Ecosystem: The Node Package Manager (NPM) is one of the largest open-source ecosystems in the world. This gives developers access to thousands of libraries and tools that can accelerate microservices development.
  • JavaScript Everywhere: Node.js allows developers to use JavaScript for both server-side and client-side programming. This streamlines development and fosters better collaboration between frontend and backend teams.
  • Scalability: Node.js is designed to be highly scalable. With features like clustering and worker threads, it can efficiently distribute incoming requests across multiple processors, making it well-suited for scaling microservices.
  • Active Community and Support: Node.js has a vibrant and active community, which means robust support and regular updates. This ensures that issues are quickly resolved and new features are frequently introduced.

Go

Go, or Golang, is a statically typed, compiled programming language designed at Google. It brings several unique benefits to microservices:

  • Concurrency Model: Go’s goroutines and channels provide a simple yet powerful concurrency model. This makes it easy to build high-performing, concurrent microservices that can handle multiple tasks simultaneously.
  • Performance: Go is known for its speed and efficiency. Being a compiled language, it offers lower latency and higher throughput, making it excellent for performance-critical microservices.
  • Built-In Tools: Go comes with a rich set of built-in tools for testing, benchmarking, and profiling. This simplifies development and helps maintain high code quality in microservices projects.
  • Static Typing and Compile-Time Safety: Go’s static typing helps catch errors at compile time, leading to more reliable and maintainable code. This is particularly beneficial in large microservices projects where preventing runtime errors is crucial.
  • Simplicity and Clean Syntax: Go is designed for simplicity, which leads to clean, readable code. This is advantageous in microservices development, where maintainability and clarity are key.

Laravel

Laravel is a PHP framework known for its elegance and developer-friendliness. It provides several advantages for microservices:

  • Expressive Syntax: Laravel’s expressive and intuitive syntax simplifies development, allowing developers to focus on business logic rather than boilerplate code.
  • Rich Ecosystem: Laravel boasts a robust ecosystem of tools and libraries, such as Eloquent ORM and Blade templating. These tools accelerate microservices development by providing solutions for common challenges.
  • Built-In Features: Laravel comes with built-in features like routing, authentication, and caching, which are essential for microservices. These features simplify the development process and enhance productivity.
  • Scalability: Despite being known for monolithic applications, Laravel can be effectively used for microservices with the help of tools like Lumen (a micro-framework by Laravel). This provides a lightweight and scalable option for microservices architecture.
  • Developer Community: Laravel has a strong and active developer community. This means ample resources, tutorials, and support, which is beneficial for developing and maintaining microservices.

Conclusion

Choosing the right technology for microservices development depends on various factors, including team expertise, performance requirements, and project complexity. Node.js excels at handling concurrent requests with its non-blocking I/O model. Go offers superior performance and a robust concurrency model. Laravel provides a rich ecosystem and developer-friendly features.

Each technology has its own strengths and is suited to different scenarios. The choice ultimately hinges on the specific needs of your microservices architecture and the preferences of your development team.

Node.js vs Laravel vs Golang

]]>
https://t-jo.com/node-js_vs_go_vs_laravel_in_microservices.html/feed 0
Curl Benefits for Web Developers https://t-jo.com/curl_benefits_for_web_developers.html https://t-jo.com/curl_benefits_for_web_developers.html#respond Sun, 30 Apr 2023 18:18:03 +0000 https://t-jo.com/?p=5717 As a Web Developer, Here Are the TOP 10 Reasons Why «curl» Is Beneficial in an SSH Console Environment:

1. API and Web Service Testing 🧪:

Curl simplifies sending requests to APIs and web services, aiding in functionality testing and troubleshooting. It supports various request types (GET, POST, PUT, DELETE) and allows for transmitting different headers and data. Curl can also display detailed request and response information, which is invaluable for debugging.

2. File Downloading 📁:

Curl can download files from web servers, useful for retrieving configuration files, images, scripts, or other data. It can resume interrupted downloads, particularly helpful when dealing with large files.

3. Task Automation 🤖:

Curl can automate various tasks like file downloads, API requests, and web service testing. Scripts created with curl can perform repetitive tasks, saving time and effort. Its integration with other tools and programming languages makes curl a powerful tool for automation.

4. Information Gathering 🕵️‍♂️:

Curl can collect information from websites by extracting HTML, text, images, or other data. It can process JSON and XML responses, which is beneficial for collecting structured data.

5. Website and Server Monitoring 🖥:

Curl can monitor websites and servers by checking site availability, tracking server response times, and monitoring changes in web pages. It can also send notifications via email or other channels if it detects issues.

6. Simulation of User Agent and IP Spoofing 🕶:

Curl allows you to simulate different user agents and spoof IP addresses, which is critical when testing how APIs and websites respond to various browsers or geographic locations. This can be particularly useful for developers working on applications that need to behave differently based on user-agent or IP-based rules.

7. Security Testing 🔐:

Curl is a valuable tool for security testing of web applications. It can be used to send crafted requests that test for vulnerabilities like SQL injections, XSS, and CSRF, thereby helping developers strengthen their security measures before deployment.

8. Handling Cookies and Sessions 🍪:

Curl can manage cookies and sessions, allowing developers to mimic stateful sessions while interacting with web services. This is essential for testing applications that require authenticated sessions or tracking user interactions across multiple requests.

9. Network Diagnostics and Troubleshooting 🌐:

Curl provides detailed network diagnostics that help in identifying connectivity issues, slow response times, and other network-related problems. This can be invaluable for optimizing application performance and ensuring high availability.

10. Support for Multiple Protocols 📡:

Besides HTTP, Curl supports a wide range of other protocols including FTP, SMTP, LDAP, and more. This makes it a versatile tool for developers who need to interact with different network services during the development and testing phases.

CheatSheet — curl commands

My LinkedIn post

]]>
https://t-jo.com/curl_benefits_for_web_developers.html/feed 0
Switching to mpm_event and HTTP/2 with php-fpm in Ubuntu https://t-jo.com/switching-to-mpm_event-and-http-2-with-php-fpm-in-ubuntu.html https://t-jo.com/switching-to-mpm_event-and-http-2-with-php-fpm-in-ubuntu.html#respond Sat, 05 Feb 2022 23:30:21 +0000 https://t-jo.com/?p=5733 To use mpm_event and support HTTP/2, you should disable all versions of PHP that rely on mpm_prefork. Then, you can configure php-fpm for each version of PHP you want to use.

Steps

  1. Disable all versions of PHP using mpm_prefork:

    Find out which PHP versions are active:

    apache2ctl -M | grep php

    Then disable them:

    sudo a2dismod php7.4
    sudo a2dismod php8.0
    sudo a2dismod php8.2
  2. Disable mpm_prefork and enable mpm_event:

    Disable mpm_prefork:

    sudo a2dismod mpm_prefork

    Enable mpm_event:

    sudo a2enmod mpm_event
  3. Enable php-fpm for each version:

    Install php-fpm for each version:

    sudo apt-get install php7.4-fpm
    sudo apt-get install php8.0-fpm
    sudo apt-get install php8.2-fpm

    Enable proxy_fcgi and setenvif:

    sudo a2enmod proxy_fcgi setenvif

    Enable php-fpm configurations:

    sudo a2enconf php7.4-fpm
    sudo a2enconf php8.0-fpm
    sudo a2enconf php8.2-fpm
  4. Configure virtual hosts to use php-fpm:

    In each virtual host, replace SetHandler with:

    <FilesMatch \\.php$>
        SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    Change php7.4 to the corresponding version for each host.

  5. Restart Apache:

    sudo systemctl restart apache2

Conclusion

Now, your virtual hosts are configured to use php-fpm and support the HTTP/2 protocol.

]]>
https://t-jo.com/switching-to-mpm_event-and-http-2-with-php-fpm-in-ubuntu.html/feed 0
PHP распечатать любой массив в режиме короткий синтаксис и microtime с array_walk_recursive или php print short array syntax square https://t-jo.com/php-print-short-array-syntax-square.html https://t-jo.com/php-print-short-array-syntax-square.html#respond Fri, 02 Apr 2021 14:59:07 +0000 https://t-jo.com/?p=5611 Порой можно привести значению любого массива к нужному виду запустив рекурсивно по его значениям прописанную функцию с помощь array_walk_recursive


array_walk_recursive(
  $productsPrices,
  function( & amp; $value) {
    $value = $value / 0.85;
    $value = round($value + $value / 10, 0, PHP_ROUND_HALF_UP);
  }
);

$results = varexport($myArray, true);

Но запустив функцию микротайм можно увидеть, что данный рекурс съедает время, а порой для оптимизации это критично


$time_start = microtime(true);
$results = varexport($myArray, true);
$time_end = microtime(true);
$time = $time_end - $time_start;

Тогда приходит в голову логичная мысль, тупо распечатать этот преобразованный массив в простом виде и его так и впиндюлить в код, ну если его значения «константы» в человеческом смысле, а не программном, предположим цена продуктов.
Можно все это сделать с помощью вот этой подготовленной функции.


function varexport($expression, $return = FALSE) {
  $export = var_export($expression, TRUE);
  $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
  $array = preg_split("/\r\n|\n|\r/", $export);
  $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
  $export = join(PHP_EOL, array_filter(["["] + $array));
  if ((bool) $return) return $export;
  else echo $export;
}

$results2 = varexport($hidPrices, true);

 

]]>
https://t-jo.com/php-print-short-array-syntax-square.html/feed 0
Xdebug and PHPStorm remote debugging by EC2 instance on AWS with Load Balancer – Linux Server Ubuntu and Git https://t-jo.com/xdebug-and-phpstorm-remote-debugging-by-ec2-instance-on-aws-with-load-balancer-linux-server-ubuntu-and-git.html https://t-jo.com/xdebug-and-phpstorm-remote-debugging-by-ec2-instance-on-aws-with-load-balancer-linux-server-ubuntu-and-git.html#respond Thu, 12 Nov 2020 16:20:30 +0000 https://t-jo.com/?p=5606 This is short Note for Laravel framework get goal with this configuration — Xdebug by EC2 instance on AWS with Load Balancer – Linux Server Ubuntu with Apache and Git

You should do settings only one server before Amazon Load Balancer and open and redirect any queries from local machine to EC2 server IP address.

  • Redirect any queries your domain name from your local PC to IP — ONE EC2 instance with installed xdebug (USE SSH and your hosts file in local OS)
  • Install xdebug on your server and configuration it in config file and .htaccess file do separate settings individual specific domain
  • PHPStorm must have true settings with remote to this remote server use ssh tunnel with folders mapping your local machine
  • Don’t forgot about your Git on local PC must be same as your remote server every time! It’s well strategy for debugging without exception on Laravel and watch your backend scope!!!

 

 

Mini notes for this short instruction:

 

$ php -v

Console command does show info about your operation system, php version and xdubug module on your server if you don’t have xdebug than

 

$ apt-get install blah-blah or yum and etc (I mean xdebug)

Standard install xdebug module

 

You need configuration xdebug server in files for ubuntu by path /etc/php/7.2/mods-available/xdebug.ini You should remember only one line — We are disable remote mode for any domains — xdebug.remote_enable = 0 and comment ;xdebug.remote_connect_back = 1 or mast have 0

Another lines you do any want

Example:

zend_extension=/usr/lib/php/20170718/xdebug.so

xdebug.remote_enable = 0

;xdebug.remote_connect_back = 1

xdebug.remote_host = 127.0.0.1

xdebug.remote_port = 9000

;xdebug.remote_handler = dbgp

;xdebug.remote_mode = req

;xdebug.profiler_enable=0

;xdebug.profiler_enable_trigger=1

xdebug.remote_autostart=1

xdebug.idekey=PHPSTORM

xdebug.remote_log=»/var/log/xdebug/xdebug.log»

 

.htaccess main directory for your domain where you need debug must add option with enable remote mode. I mean must have — php_flag  xdebug.remote_enable on

## Enable .htaccess!!!

php_flag  xdebug.remote_enable on

#php_value xdebug.remote_host «your_ip_without_quotes»

#php_value xdebug.remote_port 9000

#php_value xdebug.idekey PHPSTORM

php_flag  xdebug.remote_autostart on

 

 

AND YOU MUST TURN your local xdebug port 9000 to remote server xdebug port 9000 from local console

I use MacOS then I had done this command:

ssh -R 9000:localhost:9000 j@t-jo.com

or if you use ssh key

ssh -R 9000:localhost:9000  -vv -i ~/.ssh/id_rsa_myssh my-login@my-domain.com

 

PHPStorm good video instruction with setting remote ssh and mapping folders

]]>
https://t-jo.com/xdebug-and-phpstorm-remote-debugging-by-ec2-instance-on-aws-with-load-balancer-linux-server-ubuntu-and-git.html/feed 0
Как установить node.js на ISPManager с защитой Nginx? https://t-jo.com/kak-ustanovit-node-js-na-ispmanager-s-zashhitoj-nginx.html https://t-jo.com/kak-ustanovit-node-js-na-ispmanager-s-zashhitoj-nginx.html#respond Mon, 03 Feb 2020 15:28:06 +0000 https://t-jo.com/?p=4280 Собственно к чему вся эта статья написана? Я занимаюсь профессиональной поддержкой данного стека и разработкой скриптов в данном направлении, поэтому если Вам требуется, что-то сделать и Ваша команда не может разобраться с поставленной задачей, то пожалуйста, обращайтесь. joker@t-jo.com

Прошло не мало времени, прежде чем я добился вменяемых результатов по интеграции nodejs на Linux сервер с панелью управления для веб сайтов ISPManager.
После данной установки появилась возможность интегрировать другие интернет приложения на базе Ноды.

На первый взгляд казалось пустяковое дело сделать такую интеграцию, а слюни так текли, так как тут отлично крутяться на этой панели много сайтов на самых разных CMS: Битрикс, Webasyst Shop-Script, Magento, Drupal, WordPress, CS-Cart, OpenCart, PrestaShop с абсолютно разными базами данных MySQL, PostgreSQL, MongoDB. Очен нужно было интегрировать это решение плюс потому что таким образом я получил отличную бэкап систему на базе ISPManager панели и мне не нужно было поднимать дополнительный сервер или VDS/VPS под ноду.

Сэкономил денег и получил рабочее решение.
Вот Вам пример сайта на NODE.JS сделанного на Express модуле, но можно сделать и любой другой, если попросите.
https://nodejs.t-jo.com/

В тонкости всех настроек и проблем при установке я вдаваться не буду, но если попытаетесь такое сделать и после первой недели у Вас начнут опускаться руки, так как будут всплывать непредвиденные проблемы, то обращайтесь. Я и моя команда специалистов Вам поможем сэкономить кучу времени.

]]>
https://t-jo.com/kak-ustanovit-node-js-na-ispmanager-s-zashhitoj-nginx.html/feed 0
Example PHP-FPM — Apache — Nginx(proxy) with SSL. Ubuntu EC2 AWS https://t-jo.com/example-php-fpm-apache-nginxproxy-with-ssl-ubuntu-ec2-aws.html https://t-jo.com/example-php-fpm-apache-nginxproxy-with-ssl-ubuntu-ec2-aws.html#respond Sat, 01 Jun 2019 22:33:25 +0000 https://t-jo.com/?p=5760 Setting Up PHP-FPM, Apache, and Nginx with SSL on Ubuntu

This guide will walk you through setting up a server where Nginx serves static frontend files and acts as a reverse proxy to Apache, which handles PHP requests via PHP-FPM. We’ll also configure SSL with Let’s Encrypt’s Certbot to ensure secure connections.

1. Install and Configure Nginx

Install Nginx

sudo apt update
sudo apt install nginx

Configure Nginx

Create a configuration file for your site at /etc/nginx/sites-available/site1:

<server>
    listen 80;
    server_name site1.com www.site1.com;
    root /var/www/site1/public;
    index index.html index.htm index.php;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~* \.(html|xml|txt|pdf|js|css|jpg|jpeg|png|gif|ico|svg|webp)$ {
        root /var/www/site1/public;
        expires 1y; # Set long-term caching for static files
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    location ~* \.php$ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

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

    listen 443 ssl; # SSL for HTTPS
    ssl_certificate /etc/letsencrypt/live/site1.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/site1.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
</server>

Activate the Site and Restart Nginx

sudo ln -s /etc/nginx/sites-available/site1 /etc/nginx/sites-enabled/
sudo systemctl restart nginx

2. Install and Configure Apache

Install Apache and PHP-FPM

sudo apt update
sudo apt install apache2 php-fpm

Configure Apache to Use PHP-FPM

Create a configuration file for your site at /etc/apache2/sites-available/site1.conf:

<VirtualHost *:8080>
    ServerName site1.com
    DocumentRoot /var/www/site1/public

    <Directory /var/www/site1/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/site1-error.log
    CustomLog ${APACHE_LOG_DIR}/site1-access.log combined
</VirtualHost>

Enable Apache Configuration and Required Modules

sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.2-fpm
sudo a2ensite site1.conf
sudo systemctl restart apache2

3. Configure PHP-FPM

Ensure PHP-FPM is Running

sudo systemctl start php8.2-fpm
sudo systemctl enable php8.2-fpm

4. Configure SSL with Let’s Encrypt Certbot

Install Certbot

sudo apt update
sudo apt install certbot python3-certbot-nginx

Obtain and Configure SSL Certificate

sudo certbot --nginx -d site1.com -d www.site1.com

Certbot will automatically update your Nginx configuration and set up SSL certificates.

5. Update Hosts File

Add your domain to the /etc/hosts file for local testing:

127.0.0.1 site1.com
127.0.0.1 www.site1.com

6. Restart Services

sudo systemctl restart nginx
sudo systemctl restart apache2

Now you have a server configured with Nginx serving static files and acting as a reverse proxy to Apache, which handles PHP requests via PHP-FPM. Nginx is configured to listen on ports 80 and 443 (SSL) with certificates managed by Let’s Encrypt, ensuring secure connections and optimized performance for static files according to Google Page Speed recommendations.

]]>
https://t-jo.com/example-php-fpm-apache-nginxproxy-with-ssl-ubuntu-ec2-aws.html/feed 0