WordPress с Nginx на Ubuntu 22.04

How can we help?

WordPress с Nginx на Ubuntu 22.04

Навигация

Обновляемся:

sudo apt update && sudo apt upgrade -y

Ставим утилиты:

sudo apt install curl git wget unzip -y

Импортируем репозиторий, ставим Nginx, включаем его при загрузке системы:

sudo add-apt-repository ppa:ondrej/nginx-mainline -y
sudo apt update
sudo apt install nginx-core nginx-common nginx nginx-full
sudo systemctl enable nginx --now

Ставим и настраивам брандмауер:

sudo apt install ufw -y
sudo ufw allow 'Nginx Full'
sudo ufw allow 'OpenSSH'
sudo ufw enable

Ставим и настраиваем базу данных:

curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash -s -- --mariadb-server-version=10.6
sudo apt update
sudo apt install mariadb-server mariadb-client -y
mariadb --version
sudo systemctl status mariadb
sudo systemctl enable mariadb --now
sudo mysql_secure_installation
sudo mariadb-secure-installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] Y <---- Type Y then press the ENTER KEY.
Enabled successfully!
Reloading privilege tables..
 ... Success!


You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] Y <---- Type Y then press the ENTER KEY.
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y <---- Type Y then press the ENTER KEY.
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y <---- Type Y then press the ENTER KEY.
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

Установка и настройка PHP:

sudo add-apt-repository ppa:ondrej/php -y
sudo apt update && sudo apt upgrade
sudo apt install php8.1-fpm php8.1-cli php8.1-common php8.1-mbstring php8.1-xmlrpc php8.1-soap php8.1-gd php8.1-xml php8.1-intl php8.1-mysql php8.1-cli php8.1-ldap php8.1-zip php8.1-curl php8.1-opcache php8.1-readline php8.1-xml php8.1-gd -y
sudo systemctl enable php8.1-fpm --now

Ставим WordPress:

sudo wget https://wordpress.org/latest.zip
sudo mkdir -p /var/www/html/wordpress
sudo unzip latest.zip -d /var/www/html/
sudo chown -R www-data:www-data /var/www/html/wordpress/
sudo find /var/www/html/wordpress -type d -exec chmod 755 {} \;
sudo find /var/www/html/wordpress -type f -exec chmod 644 {} \;

Создаем базу данных для WordPress:

sudo mariadb -u root
CREATE DATABASE WORDPRESSDB;
CREATE USER 'WPUSER'@localhost IDENTIFIED BY 'PASSWORD';
GRANT ALL PRIVILEGES ON WORDPRESSDB.* TO WPUSER@localhost IDENTIFIED BY 'PASSWORD';
FLUSH PRIVILEGES;
EXIT;

Настраиваем WordPress:

cd /var/www/html/wordpress/
sudo mv wp-config-sample.php wp-config.php
sudo nano wp-config.php

/** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */ 
define( 'DB_NAME', 'WORDPRESSDB' );
/** MySQL database username */ 
define( 'DB_USER', 'WPUSER );
/** MySQL database password */
define( 'DB_PASSWORD', 'PASSWORD' );
/** MySQL hostname, change the IP here if external DB set up */ 
define( 'DB_HOST', 'localhost' );
/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
 
/** Save files direct method## */
define( 'FS_METHOD', 'direct' );
/** Increase memory limit, 256MB is recommended## */
define('WP_MEMORY_LIMIT', '256M');
/** change WordPress database table prefix if wanted## */
$table_prefix = 'wp_';

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

define('AUTH_KEY',         'Z%[J-:)X8tzK:Hx]RmF;&/r]uq!FSF9+XOkZ4e(rN1=>>uA/yOf)r+T a04S#lT^');
define('SECURE_AUTH_KEY',  'C.[1Sj3&FXI;wkf@XFL+H|WPzm.C7:e<)+idoWkP>6QISV`+Ql/s1Q #RVz<>|8F');
define('LOGGED_IN_KEY',    'k$6-pJj+;{Jp^GZI=0?>g!4=1]`T+Wd^M@Nu9.E1aZAp3l7xMf+Zp.R|}2(FE<J#');
define('NONCE_KEY',        '$>v1AZkrfyC#/kC3,X]2`aHX[Fd1nKlH4JROaKnlSYxd=G+*G=q(TO(@%x%0Xs.P');
define('AUTH_SALT',        'SVK0wG)bq>`mtOoc-cIj1/{}~Z%}1H+2L]#{jU,Ysvt.y=$!(Tk+[+$5E >F!:*d');
define('SECURE_AUTH_SALT', 'KXP E<QPC16a-yZK$h_YW G&zI(FrS9?QDf+3|8&oF>LxtWiVV>%5}@(|-A_tz/K');
define('LOGGED_IN_SALT',   'G!8vh6{g|vw>-BD^xb?)pw[0PN zYP!Ys>~JNS<UHMf@P`K=s6jcbqd%,FF?mDa|');
define('NONCE_SALT',       'i>/wp+u`7:;4J1G6~@@GexqvOB6:orLM?enc99=1_deFgxrIS/#-zWQ`^*rp%yqt');

Далее конфигурируем Nginx:

sudo nano /etc/nginx/sites-available/example.com.conf

server {

  listen 80;
  listen [::]:80;
  server_name www.wifikazan.ga wifikazan.ga;

  root /var/www/html/wordpress;

  index index.php index.html index.htm index.nginx-debian.html;


  location / {
  try_files $uri $uri/ /index.php?$args;
 }

  location ~* /wp-sitemap.*\.xml {
    try_files $uri $uri/ /index.php$is_args$args;
  }

  client_max_body_size 128M;

  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;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 128k;
    fastcgi_intercept_errors on;
  }

 gzip on;
 gzip_comp_level 6;
 gzip_min_length 1000;
 gzip_proxied any;
 gzip_disable "msie6";
 gzip_types
     application/atom+xml
     application/geo+json
     application/javascript
     application/x-javascript
     application/json
     application/ld+json
     application/manifest+json
     application/rdf+xml
     application/rss+xml
     application/xhtml+xml
     application/xml
     font/eot
     font/otf
     font/ttf
     image/svg+xml
     text/css
     text/javascript
     text/plain
     text/xml;

  # assets, media
  location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|>      expires    90d;
      access_log off;
  }

  # svg, fonts
  location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff2?)$ {
      add_header Access-Control-Allow-Origin "*";
      expires    90d;
      access_log off;
  }

  location ~ /\.ht {
      access_log off;
      log_not_found off;
      deny all;
  }
}

sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Конфигурация PHP.ini

sudo nano /etc/php/8.1/fpm/php.ini

##increase upload max size recommend 50 to 100mb##
upload_max_filesize = 100MB
##increase post max size recommend 50 to 100mb##
post_max_size = 100MB
## increase max execution time recommend 150 to 300##
max_execution_time = 300
## increase GET/POST/COOKIE input variables recommend 5000 to 10000##
max_input_vars = 5000
## increase memory limit recommend 256mb or 512mb## MAKE SURE THIS MATCHES THE MB SETTING IN YOUR WP-CONFIG.CONF
memory_limit = 256M

sudo systemctl restart php8.1-fpm

sudo nano /etc/nginx/sites-available/example.com
client_max_body_size 100M;

sudo nginx -t
sudo systemctl restart nginx

Установить фронтенд WordPress:

##go to installation address##
https://www.yoursite.com
##alternative url##
https://www.yoursite.com/wp-admin/install.php

Защитите Nginx с помощью бесплатного SSL-сертификата Let’s Encrypt:

sudo apt install python3-certbot-nginx -y
sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

# При желании вы можете настроить задание cron для автоматического обновления сертификатов. Certbot предлагает сценарий, который делает это автоматически, и вы можете сначала протестировать, чтобы убедиться, что все работает, выполнив пробный запуск.
sudo certbot renew --dry-run

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/wifikazan.ga.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Simulating renewal of an existing certificate for www.wifikazan.ga and wifikazan.ga

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/www.wifikazan.ga.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Simulating renewal of an existing certificate for www.wifikazan.ga

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations, all simulated renewals succeeded:
  /etc/letsencrypt/live/wifikazan.ga/fullchain.pem (success)
  /etc/letsencrypt/live/www.wifikazan.ga/fullchain.pem (success)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Если все ОК
sudo crontab -e

00 00 */1 * * /usr/sbin/certbot-auto renew

Иногда вы можете видеть, что ваши плагины дают вам ошибку сохранения сеанса, и это может произойти, если права пользователя не в порядке в / var / lib / php / sessions исправляется так:

sudo chown -R www-data:www-data /var/lib/php/sessions/

если что-то пойдет не так, восстановите резервную копию:

sudo cp /etc/php/8.1/fpm/backup-php.ini /etc/php/8.1/fpm/php.ini