Как установить wordpress на linux
Перейти к содержимому

Как установить wordpress на linux

  • автор:

Как установить WordPress на Ubuntu 20.04 | 18.04 с Nginx и Let’s Encrypt

hosting.energy недорогой хостинг сайтов

Это краткое руководство показывает студентам и новым пользователям, как установить WordPress на Ubuntu 18.04 | 20.04 с HTTP-сервером Nginx и SSL-сертификатами Let’s Encrypt.

WordPress, бесплатная система управления контентом с открытым исходным кодом, которая устанавливается на большее количество серверов, чем любая другая CMS, проста в установке и управлении.

Когда вы ищете CMS для запуска своего контента в Интернете, WordPress, вероятно, должен стать для вас отправной точкой. И если вы хотите узнать, как легко установить и управлять им, то этот пост — все, что вам нужно.

Чтобы узнать больше о WordPress, посетите их домашнюю страницу

Чтобы начать установку WordPress, выполните следующие действия:

Шаг 1. Установите HTTP-сервер Nginx

WordPress требует наличия веб-сервера для работы, а Nginx — один из самых популярных веб-серверов с открытым исходным кодом, доступных сегодня.

Чтобы установить Nginx в Ubuntu, выполните следующие команды:

После установки Nginx приведенные ниже команды можно использовать для остановки , запуска и включения службы Nginx, которая всегда запускается с загрузкой сервера.

Чтобы проверить, установлен ли и работает ли Nginx, откройте свой веб-браузер и перейдите к IP-адресу или имени хоста сервера.

Если вы видите указанную выше страницу в своем браузере, значит, Nginx работает должным образом.

Шаг 2: Установите сервер базы данных MariaDB

Вам также понадобится сервер базы данных для запуска WordPress. Сервер базы данных — это место, где хранится контент WordPress.

Настоящим сервером базы данных с открытым исходным кодом, который вы можете использовать с WordPress, является сервер базы данных MariaDB. Это быстрый, безопасный и используемый по умолчанию сервер почти для всех серверов Linux.

Чтобы установить MariaDB, выполните следующие команды:

sudo apt-get install mariadb-server mariadb-client

После установки MariaDB следующие команды можно использовать для остановки , запуска и включения службы MariaDB, чтобы она всегда запускалась при загрузке сервера.

Затем запустите приведенные ниже команды, чтобы защитить сервер базы данных паролем root, если вам не было предложено сделать это во время установки.

При появлении запроса ответьте на приведенные ниже вопросы, следуя инструкциям

  • Enter current password for root (enter for none): Just press the Enter
  • 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 установлена ​​и работает, войдите в консоль базы данных, используя следующие команды:

sudo mysql -u root -p

при появлении запроса введите пароль root.

Если вы видите экран, похожий на показанный выше, значит сервер успешно установлен.

Шаг 3. Установите PHP 7.4 и связанные модули

WordPress — это приложение на основе PHP, и для его запуска требуется PHP. Поскольку в некоторых версиях Ubuntu нет последней версии PHP, вы можете добавить сторонний репозиторий PPA для установки PHP оттуда.

Приведенная ниже команда добавит сторонний PPA в Ubuntu.

Затем обновите и обновите до PHP 7.4.

sudo apt update

Затем выполните приведенные ниже команды, чтобы установить PHP 7.4 и связанные модули.

sudo apt install php7.4-fpm php7.4-common php7.4-mysql php7.4-gmp php7.4-curl php7.4-intl php7.4-mbstring php7.4-xmlrpc php7.4-gd php7.4-xml php7.4-cli php7.4-zip

После установки PHP 7.4 перейдите и настройте некоторые базовые параметры, которые могут потребоваться для правильной работы WordPress.

Выполните команды ниже, чтобы открыть PHP

Ниже приведены хорошие настройки для большинства веб-сайтов WordPress.

После этого должен быть установлен PHP 7.4 с некоторыми базовыми настройками, чтобы WordPress мог работать.

Шаг 4: Создайте базу данных WordPress

Когда все серверы установлены выше, пора приступить к настройке среды WordPress. Сначала выполните следующие шаги, чтобы создать пустую базу данных для использования WordPress.

Войдите в консоль базы данных MariaDB, используя следующие команды:

sudo mysql -u root -p

Затем создайте базу данных с именем wpdb

CREATE DATABASE wpdb ;

Cоздайте пользователя базы данных с именем wpdbuser и установите пароль

CREATE USER ‘ wpdbuser ‘@’localhost’ IDENTIFIED BY ‘ new_password_here ‘;

Затем предоставьте пользователю полный доступ к базе данных.

GRANT ALL ON wpdb .* TO ‘ wpdbuser ‘@’localhost’ WITH GRANT OPTION;

Наконец, сохраните изменения и выйдите.

Шаг 5: Загрузите WordPress

На этом этапе WordPress готов к загрузке и установке. Используйте команды ниже, чтобы загрузить последнюю версию WordPress.

Затем запустите команду ниже, чтобы позволить www-data пользователю владеть каталогом WordPress.

Шаг 6. Настройте Nginx

Ниже вы настраиваете файл Nginx VirtualHost для создаваемого сайта WordPress. Этот файл определяет, как обрабатываются и обрабатываются клиентские запросы.

Выполните приведенные ниже команды, чтобы создать новый файл VirtualHost с именем wordpress в каталоге /etc/nginx/sites-available/ .

sudo nano /etc/nginx/sites-available/wordpress

Ниже приведены очень хорошие настройки конфигурации для большинства сайтов WordPress на сервере Nginx. Эта конфигурация должна отлично работать.

Скопируйте содержимое ниже и сохраните в файл, созданный выше.

Сохраните файл и выйдите.

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

На этом этапе WordPress готов и может быть запущен, перейдя на IP-адрес сервера или имя хоста.

Однако, если вы хотите включить SSL или принимать веб-трафик через HTTPS, вы можете продолжить ниже, чтобы установить и настроить бесплатные SSL-сертификаты Let’s Encrypt.

Шаг 7. Установите сертификаты Let’s Encrypt Wildcard

На шаге 6 WordPress готов к использованию без SSL. Однако, если вы хотите обслуживать веб-трафик через HTTPS, необходимо установить и настроить SSL-сертификат Let’s Encrypt или другие общедоступные сертификаты.

Чтобы установить Let’s Encrypt, выполните следующие команды.

Приведенные выше команды установят инструмент certbot и все зависимости, которые позволят заставить инструмент работать.

Let’s Encrypt предлагает множество способов проверить, что вы владеете доменом, для которого хотите предоставить сертификаты SSL. Вы не сможете создавать сертификаты, если не сможете доказать, что владеете доменом, который хотите защитить.

Для сертификатов с подстановочными знаками единственный метод запроса, который принимает Let’s Encrypt, — это запрос DNS, который мы можем вызвать с помощью флага предпочтительных вызовов = dns .

Итак, чтобы сгенерировать сертификат с подстановочными знаками для домена * .example.com , вы выполните следующие команды:

sudo certbot certonly —manual —preferred-challenges=dns —email admin@example.com —server https://acme-v02.api.letsencrypt.org/directory —agree-tos -d example.com -d *.example.com

Параметры команды выше описаны ниже:

  • certonly: Obtain or renew a certificate, but do not install
  • –manual: Obtain certificates interactively
  • –preferred-challenges=dns: Use dns to authenticate domain ownership
  • –server: Specify the endpoint to use to generate
  • –agree-tos: Agree to the ACME server’s subscriber terms
  • -d: Domain name to provide certificates for

После выполнения приведенной выше команды Let’s Encrypt предоставит текстовую строку для добавления текстовой записи в вашу запись DNS …

Перейдите на портал своего поставщика DNS, добавьте текстовую запись для строки выше и сохраните.

Подождите несколько минут, прежде чем продолжить из командной строки.

Некоторые поставщики DNS используют хитрость для распространения изменений, поэтому это может зависеть от платформы вашего провайдера.

После внесенных выше изменений, и Let’s encrypt сможет подтвердить, что вы являетесь владельцем домена, вы должны увидеть успешное сообщение, как показано ниже:

Подстановочный сертификат создан и готов к использованию.

Чтобы убедиться, что сертификат готов, выполните следующие команды:

sudo certbot certificates

Это должно отобразить аналогичный экран, как показано ниже:

Теперь сертификаты Let’s Encrypt действительны в течение 90 дней … Вы захотите настроить задание crob для автоматизации процесса обновления … Для этого откройте crontab и добавьте запись ниже:

Затем добавьте строку ниже и сохраните.

0 1 * * * /usr/bin/certbot renew >> /var/log/letsencrypt/renew.log

Сохраните, и все готово!

После установки Let’s Encrypt повторно откройте созданный выше файл VirtualHost Nginx и добавьте конфигурации Let’s Encrypt для защиты вашего сайта.

Выполните команды ниже, чтобы открыть файл.

sudo nano /etc/nginx/sites-available/wordpress

Затем добавьте выделенные строки в файл VirtualHost, как показано ниже:

После вышеуказанного перезапустите Nginx и PHP 7.4-FPM.

Затем откройте браузер и перейдите к доменному имени сервера. Вы должны увидеть завершение работы мастера установки WordPress. Пожалуйста, внимательно следуйте указаниям мастера.

Затем следуйте инструкциям на экране… Выберите язык установки и нажмите «Продолжить».

Прежде чем продолжить, вам необходимо знать следующее…. Используйте информацию о подключении к базе данных, которую вы создали выше….

  • Имя базы данных
  • Имя пользователя базы данных
  • Пароль базы данных
  • Хост базы данных
  • Префикс таблицы (если вы хотите запустить более одного WordPress в одной базе данных)

Мастер будет использовать информацию из базы данных для создания файла wp-config.php в корневой папке WordPress….

Если по какой-либо причине это автоматическое создание файла не работает, не беспокойтесь… Все, что нужно сделать, это заполнить информацию из базы данных в файле конфигурации. Вы также можете просто открыть wp-config-sample.php в текстовом редакторе, ввести свою информацию и сохранить ее как wp-config.php .

Затем введите информацию о подключении к базе данных и нажмите Отправить.

После этого нажмите кнопку « Запустить установку» , чтобы WordPress завершил установку.

Затем создайте имя сайта WordPress и учетную запись бэкэнд-администратора…. затем нажмите Установить WordPress

Когда вы закончите, WordPress должен быть установлен и готов к использованию

Поздравляю! Вы успешно установили WordPress CMS в Ubuntu 18.04 | 20.04. Если вы обнаружите какую-либо ошибку выше, пожалуйста, используйте форму комментария ниже, чтобы сообщить об этом.

How to Install WordPress on Ubuntu 18.04 Using LAMP Stack

How to Install WordPress on Ubuntu 18.04 Using LAMP Stack

WordPress is the most popular Content Management System (CMS) thanks to its user-friendliness and flexibility to create all manner of websites. The software can also be installed on different types of hosting, including a Virtual Private Server (VPS).

To install WordPress on your server, you can use the LAMP (Linux, Apache, MySQL, and PHP) stack. This method is ideal for when you need complete control over the WordPress back-end.

This article will cover the details of the WordPress installation on Ubuntu 18.04 using the LAMP stack, from installing the Apache server to configuring WordPress via a web browser.

How to Install WordPress Using LAMP

Before we get started, you’ll need to access the VPS using an SSH client. Check our PuTTY tutorial on how to do that.

Pro Tip

Make sure you use a root or sudo user since this method involves a few installations and configuring the firewall.

Step 1. Install and Configure the Apache Web Server

The first step to set up the LAMP stack is to install and configure the Apache server. First, we have to update and upgrade the package list on your system and upgrade the packages to the newest version. Do so by using these commands on your SSH client:

If you’re asked to enter a password, input your VPS root password and press Enter.

Now it’s time to install the Apache2 web server on your VPS. If you buy a VPS plan from Hostinger, it comes with Apache2 pre-installed. If you follow the next step, it does not harm your VPS, but you can skip it.

Run the following command to install Apache2:

Hostinger’s VPS doesn’t come with the uncomplicated firewall (UFW) pre-installed. However, if you’ve installed UFW on your VPS, it may restrict Apache’s HTTP and HTTPS traffic. To check your UFW application profiles, enter this command:

The output will look like this:

If you run that command on a default Hostinger VPS that doesn’t have UFW, it should print the following output:

Step 2. Install PHP

PHP is necessary for WordPress to communicate with the MySQL database and display dynamic content. You will also need to install additional PHP extensions for WordPress.

Run the following command to install PHP and PHP extensions at once:

When you request a directory without specifying a filename, index.html will be given the priority and hence will be displayed. You can change the priority order in the dir.conf file. Use the following command to open it using Nano text editor:

You should see the following:

The configuration to open the dir.conf file using the Nano text editor.

When loading the website, it will resolve the files from left to right. You have to place all files in the correct order of priority. For example, if you want index.php to have a higher priority than index.html, simply move index.php to the left of index.html.

Once you’ve changed the file, save it and exit by pressing CTRL+X. Then, type Y to save changes and Enter to close it.

Now you have to restart the Apache2 web server so that the changes take place. Run the following command to do so:

Create a sample PHP file in the web root directory to check whether PHP works. Use this command to go to the directory:

Then use this command to create a sample PHP file and open it using the Nano text editor:

In the text editor, insert the following code:

Save and exit the file.

Now, access the file by entering http://your-IP-adress/sample.php in your web browser. You should see this PHP info page:

PHP info page.

Pro Tip

You can find your IP address in your Hostinger hPanel under the VPS SSH Details.

We recommend removing the file after checking the installation. The PHP info displays PHP installation and server configuration, which may help cyber attackers to access your server. Use this command to delete it:

Step 3. Configure MySQL and Create a Database

Once Apache is running, the next step is to install the MySQL database. To do so, run the following command:

It’ll be necessary to enter your password. To complete the installation, press Y and Enter when prompted.

After installing MySQL on your VPS, open the MySQL terminal by typing the following command:

Set the password for the MySQL root account using this command:

Make sure to enter a strong MySQL root password in place of YOURPASSWORD.

To implement these changes, run the flush command:

Use the following command to create a WordPress database:

Now, we’ll create a MySQL user account to operate on the new WordPress database. We’ll use WordPressDB as the database name and testhostinger as the username:

Make sure to enter a strong password in place of newpassword. Once done, flush the privileges so that MySQL implements the changes.

Finally, exit MySQL by typing this command:

Step 4. Prepare to Install WordPress on Ubuntu

It’s time to prepare the WordPress installation by creating a WordPress configuration file and a WordPress directory.

Creating a WordPress.conf File

Start by creating a WordPress.conf Apache configuration file in the /etc/apache2/sites-available directory. Use the following command:

Important! Keep in mind that file and locale names are case-sensitive on Linux.

Once you run that command, you’ll get to the Nano text editor to edit the WordPress.conf file. Enable .htaccess by adding these lines to the VirtualHost block:

Close and save the file by pressing CTRL+X. Press Y and Enter when prompted.

Creating a WordPress Directory

Then, create a directory for WordPress in /var/www/. In our example, its full path will be /var/www/wordpress. To do so, use the mkdir command to create the directory:

Now, enable mod_rewrite to use the WordPress permalink feature by running the following command in the terminal:

You’ll have to restart the Apache web server by using the following command:

The next step is changing the ServerName directive in the /etc/apache2/apache2.conf file. Open the file using this command:

You’ll have to configure the ServerName directive to the server’s IP address or hostname by adding the following line to the /etc/apache2/apache2.conf file:

Close and save the file.

Now, you have to check whether the Apache configuration is correct by running the following command on the terminal:

If the configuration works fine, it should print the following output:

Output: Syntax OK window

Step 5. Download and Configure WordPress

After all the preparations are complete, it’s time to install WordPress. There are two methods – setting up WordPress via a web interface or manually editing the wp-config.php file.

Method 1. Configuring WordPress via a Browser

First, install the wget package on your VPS. This will be useful for downloading WordPress files. Run this command on the command line:

Then, use the wget command followed by the WordPress download link:

Once you have downloaded the archive file, install the unzip utility using these commands:

Now you will have to move the file to the correct directory before unzipping it. Use the command:

Then, navigate to the directory and unzip the file using these commands:

After that, use the following command to move the directory:

The last step is to remove index.html. Use the following command:

You can use the ls command to verify if the index.html file has been removed. Once that’s done, restart Apache by using these commands:

sudo systemctl restart apache2
sudo chown -R www-data:www-data /var/www/

Finish it by setting up WordPress via a web browser. Open a web browser and type in the server’s IP address. The following steps will be similar to a standard WordPress setup.

First, select a language for WordPress and click Continue.

WordPress setup - choosing the language.

A Welcome to WordPress message will appear listing the information you’ll need to complete the setup. Click on the Let’s go! button to continue.

Welcome to WordPress message - highlighting the "Let

It will take you to the main setup page. Fill in the following details:

  • Database name – enter the name you set up when configuring the WordPress database. In this case, it will be WordPressDB.
  • Username – type in the MySQL username you’ve set up for the database earlier.
  • Password – input the password you’ve created for the database user.
  • Database host – keep the default value localhost here.
  • Table prefix – leave wp_ in this field.

Click Submit to continue.

WordPress setup page, showing the form for database connection details

A new message will appear saying that WordPress can now communicate with your database. Click Run the installation.

WordPress message informing that database connection is successful - highlighting the "Run the installation" button

After that, you’ll have to enter some more information:

  • Site title – type in the WordPress website name. To optimize your site, we recommend inputting its domain name.
  • Username – create a new username you’ll use to log in to WordPress.
  • Password – create a password for the WordPress user.
  • Your email – add the email address for updates and notifications.
  • Search engine visibility – leave this box unchecked if you don’t want search engines to index your site until it is ready.

Click the Install WordPress button to finish it.

WordPress setup page - installation form

A success message will appear along with a login button. You can access WordPress straight from this page.

Success message: WordPress has been installed

Once you have logged in, you’ll be taken to the WordPress administration dashboard. Now you can start customizing the website by installing WordPress plugins and themes.

If your WordPress site does not have a domain name yet, purchase one and point the domain name to the VPS before making the website public.

Method 2. Manually Editing the wp-config.php File

Alternatively, install WordPress by manually editing the wp-config.php file. Use these commands to change your current working directory and download the WordPress archive file:

Then, run the following command to extract the archive file:

Create a .htaccess file in the /tmp directory by using this command:

Save the file by pressing CTRL+X and then Y and Enter when prompted.

Now, you have to rename the WordPress sample configuration file. By default, it’s named wp-config-sample.php. Rename it by using this command:

Create an update folder in the /var/www/html path so WordPress doesn’t run into permission issues in the future:

That command completes the initial setup. Now, we can copy the files into the document root directory:

Change the ownership of WordPress files to the www-data users and groups as the Apache web server will use them. To change the ownership, run this command:

Then, set the correct permissions for the directories and files using chmod command:

For the initial configuration, you’ll also need to generate the WordPress salts. Run this command to do this:

This command will produce unique salt values each time it runs. Copy the output and replace the dummy values in the wp-config.php file. Type in this command to open and edit the file:

The wp-config.php file also contains database configuration details at the top. Replace the DB_NAME, DB_USER, and DB_PASSWORD with the values you have set for WordPress.

Finally, add the file system method at the very bottom:

Save the file after making the changes.

Conclusion

WordPress is a popular CMS excellent for website creation. If you have VPS hosting, setting up WordPress using the LAMP stack is a great way to power your site and access its back-end.

Remember to use sudo or root user as the installation process requires administrative access. Let’s recap the steps to install WordPress CMS on a server running on Ubuntu 18.04:

  • Install Apache2 – it will be the basis for your web server.
  • Install PHP – WordPress will use it to communicate with the database. Remember to install the PHP extensions, too.
  • Set up MySQL – it’ll act as the database for all WordPress files.
  • Prepare for WordPress installation – a WordPress directory and the WordPress.conf are required for the installation process.
  • Download and install WordPress on Ubuntu – finish the process by setting up the WordPress site.

We hope this tutorial has taught you how to install and configure WordPress on Ubuntu. Go ahead and try it yourself. If you have any questions, leave them in the comment section below.

Learn What Else Your Ubuntu Can Do

Leo is a WordPress fanatic and contributor. He likes keeping up with the latest WordPress news and updates, and sharing his knowledge to help people build successful websites. When he’s not working, he contributes to WordPress documentation team and pampers his dogs.

Install and configure WordPress

WordPress is the most popular open-source blogging system and CMS on the Web. It is based on PHP and MySQL. Its features can be extended with thousands of free plugins and themes.

In this tutorial we will install WordPress on Apache2 server and create our first post.

What you’ll learn

  • How to set up WordPress
  • How to configure WordPress
  • How to create first post

What you’ll need

  • A computer running Ubuntu Server 20.04 LTS
  • This guide will also show you how to configure a database for WordPress

Originally authored by Marcin Mikołajczak
Heavily updated by Dani Llewellyn

2. Install Dependencies

To install PHP and Apache, use following command:

3. Install WordPress

We will use the release from WordPress.org rather than the APT package in the Ubuntu Archive, because this is the preferred method from upstream WordPress. This will also have fewer “gotcha” problems that the WordPress support volunteers will not be able to anticipate and therefore be unable to help with.

Create the installation directory and download the file from WordPress.org:

Note that this sets the ownership to the user www-data , which is potentially insecure, such as when your server hosts multiple sites with different maintainers. You should investigate using a user per website in such scenarios and make the files readable and writable to only those users. This will require configuring PHP-FPM to launch a separate instance per site each running as the site’s user account. In such setup the wp-config.php should (read: if you do it differently you need a good reason) be readonly to the site owner and group and other permissions set to no-access ( chmod 400 ). This is beyond the scope of this guide, however.

4. Configure Apache for WordPress

Create Apache site for WordPress. Create /etc/apache2/sites-available/wordpress.conf with following lines:

Enable the site with:

Enable URL rewriting with:

Disable the default “It Works” site with:

Or, instead of disabling the “it works” page, you may edit our configuration file to add a hostname that the WordPress installation will respond to requests for. This hostname must be mapped to your box somehow, e.g. via DNS, or edits to the client systems’ /etc/hosts file (on Windows the equivalent is C:\Windows\System32\drivers\etc\hosts ). Add ServerName as below:

Finally, reload apache2 to apply all these changes:

5. Configure database

To configure WordPress, we need to create MySQL database. Let’s do it!

Enable MySQL with sudo service mysql start .

6. Configure WordPress to connect to the database

Now, let’s configure WordPress to use this database. First, copy the sample configuration file to wp-config.php :

Next, set the database credentials in the configuration file (do not replace database_name_here or username_here in the commands below. Do replace <your-password> with your database password.):

Finally, in a terminal session open the configuration file in nano:

Find the following:

Delete those lines ( ctrl + k will delete a line each time you press the sequence). Then replace with the content of https://api.wordpress.org/secret-key/1.1/salt/. (This address is a randomiser that returns completely random keys each time it is opened.) This step is important to ensure that your site is not vulnerable to “known secrets” attacks.

Save and close the configuration file by typing ctrl + x followed by y then enter

7. Configure WordPress

Open http://localhost/ in your browser. You will be asked for title of your new site, username, password, and address e-mail. Note that the username and password you choose here are for WordPress, and do not provide access to any other part of your server — choose a username and password that are different to your MySQL (database) credentials, that we configured for WordPress’ use, and different to your credentials for logging into your computer or server’s desktop or shell. You can choose if you want to make your site indexed by search engines.

WordPress installation

You can now login under http://localhost/wp-login.php. In the WordPress Dashboard, you will see bunch of icons and options. Don’t worry, it’s easy!

Dashboard

8. Write your first post

You will notice the “Hello world!” post. Let’s delete it and write something more interesting…

All Posts

From Dashboard (http://localhost/wp-admin/), select the “Posts” icon and click on “All Posts”. Mouse over the “Hello world!” post title and select Trash.

Move to Trash

To create new post, click on the “Add New” button. You should notice a fancy WYSIWYG editor with simple (but powerful) text formatting options. You may want to switch to Text mode if you prefer pure HTML.

Let’s write something! It’s as easy, as using text processors that you know from office suites.

First post

Now, click the Publish button. You can now view your brand-new post!

9. That’s all!

Of course, this tutorial has only described basics of WordPress usage, you can do much more with this blogging platform/CMS. You can install one of thousands of available (free and commercial) plugins and themes. You can even configure it as forum (with bbPress plugin), microblogging platform (BuddyPress), eCommerce platform (WooCommerce) or extend existing WordPress features with plugins like JetPack or TinyMCE Advanced.

How To Install WordPress with LAMP on Ubuntu 22.04

Smit Pipaliya

For those who cannot afford the hustles of developing websites from scratch, there are now several content management systems (CMSs) such as WordPress that you can take advantage of to set up blogs and complete websites with a few clicks.

WordPress is one of the world’s most popular, if not the world’s most popular content management system (CMS). It is a free and open-source platform built entirely in PHP — it’s used by millions of people for running blogs, business websites, e-commerce stores, and much more. With features such as in-depth theming, thousands of plug-ins, and a huge community, WordPress is probably the most user-friendly CMS you can choose for building your website.

It is easy to install and learn, especially for persons who do not have prior website design and development knowledge. With millions of plugins and themes available, developed by an active and dedicated community of fellow users and developers, you can utilize them to tailor your blog or website to work and look just the way you want.

This blog will show you how to get your site hosted with WordPress on Ubuntu Linux. We’ll use Apache as our HTTP server and install PHP and MySQL since WordPress requires them to function. This assortment of packages is commonly referred to as a LAMP stack (Linux, Apache, MySQL, PHP). Once those packages are installed, we’ll go over the configuration of Apache and MySQL, including the initial setup of a database and user, before installing WordPress itself.

Prerequisites

  • The operating system running Ubuntu 22.04 LTS
  • A root or non-root user with Sudo privileges
  • Has stable internet connection
  • Terminal window / Command line

1. Install Apache On Ubuntu

If you have installed Apache, you can skip this. If you have not installed Apache, then just follow this article How to Install Apache on Ubuntu 22.04 LTS

2. Install And Configure MySQL On Ubuntu

If you have installed MySQL, you can skip this. If you have not installed MySQL, then just follow this article How to Install MySQL on Ubuntu 22.04

3. Install PHP 8 On Ubuntu

If you have installed PHP 8.1, you can skip this. If you have not installed PHP 8.1, then just follow this article How To Install PHP 8.1 on Ubuntu 22.04

4. Install WordPress On Ubuntu

Download the latest version of the WordPress package and extract it by issuing the commands below on the terminal:

Then move the WordPress files from the extracted folder to the Apache default root directory, /var/www/html/:

Now set appropriate permissions on the website (/var/www/html) directory. It should be owned by the Apache2 user and group called www-data.

Checkout This Tool: Open Port Check Tool

5. Create WordPress Database On MySQL

Execute the command below and provide the root user password, then hit Enter to move to the MySQL shell:

At the MySQL shell, type the following commands, pressing Enter after each MySQL command line. Remember to use your own, valid values for database name, database user, and also use a secure and robust password as database user password:

Next, move into your website’s document root and create a wp-config.php file from the sample configuration file provided as shown.

Then open the wp-config.php configuration file for editing.

After updating your wp-config.php file, press CTRL+X, Y, and Enter key to save the wp-config.php file.

Afterward, restart the webserver and MySQL service, Run the following command:

6. Completing the WordPress Installation Via Web

Open your web browser, then enter your domain name or server address as shown.

Once the WordPress web installer loads, pick the language you wish to use for installation and click Continue.

Next, set your site’s title, administrative username, password, and email to manage your site content. Then click Install WordPress.

Once the WordPress installation is complete, click on Log in to access your site’s administrative login page.

Now log into your new WordPress website using your administrative credentials (username and password created above) and start to customize your site from Dashboard.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *