Как установить PhpMyAdmin с бесплатным Let's Encrypt SSL на Ubuntu 22.04
Это руководство существует для этих версий ОС
- Ubuntu 22.04 (Jammy Jellyfish)
- Ubuntu 11.04 (Natty Narwhal)
На этой странице
- Предпосылки
- Установите Nginx, MariaDB и PHP
- Установите phpMyAdmin
- Настройка базы данных MariaDB
- Настройка Nginx для phpMyAdmin
- Защитите phpMyAdmin с помощью Let’s Encrypt SSL
- Доступ к phpMyAdmin
- Заключение
phpMyAdmin — это бесплатное веб-приложение с открытым исходным кодом, используемое для управления базами данных через веб-браузер. Он предоставляет простой и удобный веб-интерфейс, который помогает администраторам баз данных выполнять несколько задач, управлять учетными записями пользователей и привилегиями, импортировать и экспортировать данные, выполнять операторы SQL и многое другое. Он написан на PHP, что дает начинающим пользователям возможность взаимодействовать со своими базами данных MySQL.
В этом руководстве мы объясним, как установить phpMyAdmin с Nginx в Ubuntu 22.04.
Предпосылки
- Сервер под управлением Ubuntu 22.04.
- Действительное доменное имя указано на вашем сервере.
- На вашем сервере настроен пароль root.
Установите Nginx, MariaDB и PHP
Во-первых, вам нужно будет установить веб-сервер Nginx, MariaDB, PHP и другие необходимые расширения PHP на вашем сервере. Вы можете установить их все с помощью следующей команды:
apt-get install nginx mariadb-server php php-cli php-mysql php-mbstring php-zip php-gd php-json php-curl php-fpm -y
После установки всех пакетов можно переходить к следующему шагу.
Установите phpMyAdmin
По умолчанию пакет phpMyAdmin доступен в стандартном репозитории Ubuntu 22.04. Вы можете установить его, просто выполнив следующую команду:
apt-get install phpmyadmin -y
Поскольку мы используем веб-сервер Nginx, вы можете просто нажать TAB, а затем ENTER, чтобы обойти это приглашение. Вам будет предложено настроить базу данных для использования phpMyAdmin.
Выберите Да и нажмите Enter, чтобы продолжить. Вам будет предложено выбрать и подтвердить пароль для приложения phpMyAdmin, как показано ниже:
Введите желаемый пароль и нажмите Enter, чтобы завершить установку.
Настроить базу данных MariaDB
По умолчанию MariaDB не защищена. Поэтому защитите MariaDB и установите корневой пароль MariaDB с помощью следующей команды:
mysql_secure_installation
Ответьте на все вопросы, как показано ниже:
Enter current password for root (enter for none): Set root password? [Y/n] Y New password: Re-enter new password: Remove anonymous users? [Y/n] Y Disallow root login remotely? [Y/n] Y Remove test database and access to it? [Y/n] Y Reload privilege tables now? [Y/n] Y
После защиты MariaDB рекомендуется создать отдельного пользователя для подключения phpMyAdmin и управления базой данных.
Для этого войдите в оболочку MariaDB с помощью следующей команды:
mysql -u root -p
Укажите свой пароль root при появлении запроса, затем создайте нового пользователя с помощью следующей команды:
MariaDB [(none)]> create user identified by 'password';
Затем предоставьте все привилегии пользователю с помощью следующей команды:
MariaDB [(none)]> grant all privileges on *.* to with grant option;
Затем сбросьте привилегии и выйдите из оболочки MariaDB, используя следующую команду:
MariaDB [(none)]> flush privileges;
MariaDB [(none)]> exit;
Как только вы закончите, вы можете перейти к следующему шагу.
Настроить Nginx для phpMyAdmin
Затем вам нужно будет создать блок виртуального хост-сервера Nginx для размещения phpMyAdmin. Вы можете создать его с помощью следующей команды:
nano /etc/nginx/conf.d/phpmyadmin.conf
Добавьте следующие строки:
server { listen 80; listen [::]:80; server_name phpmyadmin.example.com; root /usr/share/phpmyadmin/; index index.php index.html index.htm index.nginx-debian.html; access_log /var/log/nginx/phpmyadmin_access.log; error_log /var/log/nginx/phpmyadmin_error.log; location / { try_files $uri $uri/ /index.php; } location ~ ^/(doc|sql|setup)/ { deny all; } location ~ \.php$ { fastcgi_pass unix:/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; include snippets/fastcgi-php.conf; } location ~ /\.ht { deny all; } }
Сохраните и закройте файл. Затем проверьте Nginx на наличие синтаксической ошибки с помощью следующей команды:
nginx -t
Вы должны получить следующий результат:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Наконец, перезапустите службу Nginx, чтобы применить изменения:
systemctl restart nginx
Вы также можете проверить статус Nginx с помощью следующей команды:
systemctl status nginx
Вы должны увидеть следующий вывод:
? nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2022-06-12 04:37:05 UTC; 6s ago Docs: man:nginx(8) Process: 20020 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Process: 20021 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Main PID: 20022 (nginx) Tasks: 2 (limit: 2292) Memory: 2.6M CPU: 33ms CGroup: /system.slice/nginx.service ??20022 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;" ??20023 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" Jun 12 04:37:05 ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server... Jun 12 04:37:05 ubuntu systemd[1]: Started A high performance web server and a reverse proxy server.
Затем измените владельца и права доступа к каталогу phpMyAdmin:
chown -R www-data:www-data /usr/share/phpmyadmin/
chmod -R 755
Защитите phpMyAdmin с помощью Let's Encrypt SSL
Прежде чем начать, вам нужно будет установить клиент Certbot, чтобы загрузить и установить Let's Encrypt SSL.
Сначала добавьте репозиторий Certbot с помощью следующей команды:
add-apt-repository ppa:ahasenack/certbot-tlssni01-1875471
Затем обновите репозиторий и установите клиент Certbot с помощью следующей команды:
apt-get update -y
apt-get install certbot python3-certbot-nginx -y
После установки Certbot выполните следующую команду, чтобы загрузить и установить Let's Encrypt SSL для своего домена:
certbot --nginx -d phpmyadmin.example.com
Вам будет предложено указать адрес электронной почты и принять условия обслуживания, как показано ниже:
Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Enter email address (used for urgent renewal and security notices) (Enter 'c' to cancel): - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Please read the Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must agree in order to register with the ACME server at https://acme-v02.api.letsencrypt.org/directory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (A)gree/(C)ancel: A - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Would you be willing to share your email address with the Electronic Frontier Foundation, a founding partner of the Let's Encrypt project and the non-profit organization that develops Certbot? We'd like to send you email about our work encrypting the web, EFF news, campaigns, and ways to support digital freedom. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Y)es/(N)o: Y Obtaining a new certificate Performing the following challenges: http-01 challenge for phpmyadmin.example.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/phpmyadmin
Затем выберите, следует ли перенаправлять HTTP-трафик на HTTPS:
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Введите 2 и нажмите Enter, чтобы завершить установку.
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/phpmyadmin - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://phpmyadmin.example.com You should test your configuration at: https://www.ssllabs.com/ssltest/analyze.html?d=phpmyadmin.example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/phpmyadmin.example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/phpmyadmin.example.com/privkey.pem Your cert will expire on 2022-09-12. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le
Доступ к phpMyAdmin
Теперь откройте веб-браузер и введите URL-адрес https://phpmyadmin.eample.com. Вы будете перенаправлены на страницу входа в phpMyAdmin:
Введите имя пользователя и пароль администратора и нажмите кнопку «Перейти». Вы должны увидеть панель инструментов phpMyAdmin по умолчанию на следующей странице:
Заключение
Поздравляем! вы успешно установили phpMyAdmin и защитили его с помощью Let’s Encrypt SSL в Ubuntu 22.04. Теперь вы можете подключиться к phpMyAdmin, управлять своими базами данных и выполнять несколько задач через веб-браузер.