如何在Ubuntu 20.04上安装Linux,Nginx,MySQL,PHP(LEMP堆栈)

介绍 (Introduction)

The LEMP software stack is a group of software that can be used to serve dynamic web pages and web applications written in PHP. This is an acronym that describes a Linux operating system, with an Nginx (pronounced like “Engine-X”) web server. The backend data is stored in the MySQL database and the dynamic processing is handled by PHP.

LEMP软件堆栈是一组软件,可用于为用PHP编写的动态网页和Web应用程序提供服务。 这是一个首字母缩写词,用于描述L inux操作系统和Nginx(发音为“ E ngine-X”)Web服务器。 后端数据存储在M ySQL数据库中,动态处理由P HP处理。

This guide demonstrates how to install a LEMP stack on an Ubuntu 20.04 server. The Ubuntu operating system takes care of the first requirement. We will describe how to get the rest of the components up and running.

本指南演示了如何在Ubuntu 20.04服务器上安装LEMP堆栈。 Ubuntu操作系统满足了第一个要求。 我们将描述如何启动和运行其余组件。

先决条件 (Prerequisites)

In order to complete this tutorial, you will need access to an Ubuntu 20.04 server as a regular, non-root sudo user, and a firewall enabled on your server. To set this up, you can follow our initial server setup guide for Ubuntu 20.04.

为了完成本教程,您将需要以常规的非root用户sudo用户身份访问Ubuntu 20.04服务器,并在服务器上启用防火墙。 要进行设置,您可以遵循我们的Ubuntu 20.04初始服务器设置指南

第1步–安装Nginx Web服务器 (Step 1 – Installing the Nginx Web Server)

In order to display web pages to our site visitors, we are going to employ Nginx, a high-performance web server. We’ll use the apt package manager to obtain this software.

为了向网站访问者显示网页,我们将使用高性能的Web服务器Nginx。 我们将使用apt软件包管理器来获取此软件。

Since this is our first time using apt for this session, start off by updating your server’s package index. Following that, you can use apt install to get Nginx installed:

由于这是我们第一次使用apt进行此会话,因此首先更新服务器的软件包索引。 之后,您可以使用apt installapt install Nginx:

  • sudo apt update

    sudo apt更新
  • sudo apt install nginx

    sudo apt安装nginx

When prompted, enter Y to confirm that you want to install Nginx. Once the installation is finished, the Nginx web server will be active and running on your Ubuntu 20.04 server.

出现提示时,输入Y确认要安装Nginx。 安装完成后,Nginx Web服务器将处于活动状态并在您的Ubuntu 20.04服务器上运行。

If you have the ufw firewall enabled, as recommended in our initial server setup guide, you will need to allow connections to Nginx. Nginx registers a few different UFW application profiles upon installation. To check which UFW profiles are available, run:

如果按照我们的初始服务器安装指南中的建议启用了ufw防火墙,则需要允许连接到Nginx。 Nginx在安装时会注册一些不同的UFW应用程序配置文件。 要检查哪些UFW配置文件可用,请运行:

  • sudo ufw app list

    sudo ufw应用程序列表

   
   
Output
Available applications: Nginx Full Nginx HTTP Nginx HTTPS OpenSSH

It is recommended that you enable the most restrictive profile that will still allow the traffic you need. Since you haven’t configured SSL for your server in this guide, you will only need to allow regular HTTP traffic on port 80.

建议您启用限制性最强的配置文件,该配置文件仍将允许您需要的流量。 由于在本指南中尚未为服务器配置SSL,因此只需要在端口80上允许常规HTTP通信即可。

Enable this by typing:

通过键入以下内容启用此功能:

  • sudo ufw allow 'Nginx HTTP'

    sudo ufw允许'Nginx HTTP'

You can verify the change by running:

您可以通过运行以下命令来验证更改:

  • sudo ufw status

    sudo ufw状态

This command’s output will show that HTTP traffic is now allowed:

此命令的输出将显示现在允许HTTP通信:


   
   
Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Nginx HTTP ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Nginx HTTP (v6) ALLOW Anywhere (v6)

With the new firewall rule added, you can test if the server is up and running by accessing your server’s domain name or public IP address in your web browser.

添加新的防火墙规则后,您可以通过在Web浏览器中访问服务器的域名或公共IP地址来测试服务器是否已启动并正在运行。

If you do not have a domain name pointed at your server and you do not know your server’s public IP address, you can find it by running the following command:

如果没有指向服务器的域名,并且您不知道服务器的公共IP地址,则可以通过运行以下命令来找到它:

  • ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

    ip addr显示eth0 | grep inet | awk'{print $ 2; }'| sed's /\/.*$//'

This will print out a few IP addresses. You can try each of them in turn in your web browser.

这将打印出一些IP地址。 您可以依次在网络浏览器中尝试使用它们。

As an alternative, you can check which IP address is accessible, as viewed from other locations on the internet:

作为替代方案,您可以检查从互联网上其他位置查看的哪个IP地址可访问:

  • curl -4 icanhazip.com

    卷曲-4 icanhazip.com

Type the address that you receive in your web browser and it will take you to Nginx’s default landing page:

输入您在网络浏览器中收到的地址,它将带您到Nginx的默认登录页面:

http://server_domain_or_IP

If you see this page, it means you have successfully installed Nginx and enabled HTTP traffic for your web server.

如果看到此页面,则表明您已成功安装Nginx并为Web服务器启用了HTTP流量。

第2步-安装MySQL (Step 2 — Installing MySQL)

Now that you have a web server up and running, you need to install the database system to be able to store and manage data for your site. MySQL is a popular database management system used within PHP environments.

现在,您已经启动并运行了Web服务器,您需要安装数据库系统,以便能够存储和管理站点数据。 MySQL是在PHP环境中使用的流行数据库管理系统。

Again, use apt to acquire and install this software:

同样,使用apt来获取并安装此软件:

  • sudo apt install mysql-server

    sudo apt安装mysql服务器

When prompted, confirm installation by typing Y, and then ENTER.

出现提示时,请键入Y ,然后按ENTER确认安装。

When the installation is finished, it’s recommended that you run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system. Start the interactive script by running:

安装完成后,建议您运行MySQL随附的安全脚本。 该脚本将删除一些不安全的默认设置,并锁定对数据库系统的访问。 通过运行以下命令来启动交互式脚本:

  • sudo mysql_secure_installation

    须藤mysql_secure_installation

This will ask if you want to configure the VALIDATE PASSWORD PLUGIN.

这将询问您是否要配置VALIDATE PASSWORD PLUGIN

Note: Enabling this feature is something of a judgment call. If enabled, passwords which don’t match the specified criteria will be rejected by MySQL with an error. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.

注意:启用此功能只是一个判断。 如果启用,与指定条件不匹配的密码将被MySQL拒绝并出现错误。 禁用验证是很安全的,但是您应该始终对数据库凭据使用强而独特的密码。

Answer Y for yes, or anything else to continue without enabling.

Y (是),或其他任何继续不启用。

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No:

If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2 for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.

如果回答“是”,则将要求您选择密码验证级别。 请记住,如果输入2作为最强级别,则尝试设置任何不包含数字,大写,小写字母和特殊字符或基于常见词典单词的密码时,都会收到错误消息。

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary              file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1

Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN, your server will next ask you to select and confirm a password for the MySQL root user. This is not to be confused with the system root. The database root user is an administrative user with full privileges over the database system. Even though the default authentication method for the MySQL root user dispenses the use of a password, even when one is set, you should define a strong password here as an additional safety measure. We’ll talk about this in a moment.

无论您是否选择设置VALIDATE PASSWORD PLUGIN ,服务器都将接下来要求您选择并确认MySQL 用户的密码。 这不要与系统根目录混淆。 数据库根用户是对数据库系统具有完全特权的管理用户。 即使MySQL超级用户的默认身份验证方法免除了使用密码, 即使设置了密码,您也应在此处定义一个强密码作为附加的安全措施。 我们稍后再讨论。

If you enabled password validation, you’ll be shown the password strength for the root password you just entered and your server will ask if you want to continue with that password. If you are happy with your current password, enter Y for “yes” at the prompt:

如果启用了密码验证,将显示您刚刚输入的根密码的密码强度,服务器将询问您是否要继续使用该密码。 如果您对当前密码感到满意,请在提示符下输入Y代表“是”:

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y

For the rest of the questions, press Y and hit the ENTER key at each prompt. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.

对于其余的问题,请按Y并在每个提示下按ENTER键。 这将删除一些匿名用户和测试数据库,禁用远程root登录,并加载这些新规则,以便MySQL立即尊重您所做的更改。

When you’re finished, test if you’re able to log in to the MySQL console by typing:

完成后,通过键入以下内容来测试是否能够登录到MySQL控制台:

  • sudo mysql

    须藤MySQL

This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. You should see output like this:

这将以管理数据库用户root身份连接到MySQL服务器,这是通过在运行此命令时使用sudo推断出来的。 您应该看到如下输出:


   
   
Output
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 22 Server version: 8.0.19-0ubuntu5 (Ubuntu) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>

To exit the MySQL console, type:

要退出MySQL控制台,请输入:

  • exit

    出口

Notice that you didn’t need to provide a password to connect as the root user, even though you have defined one when running the mysql_secure_installation script. That is because the default authentication method for the administrative MySQL user is unix_socket instead of password. Even though this might look like a security concern at first, it makes the database server more secure because the only users allowed to log in as the root MySQL user are the system users with sudo privileges connecting from the console or through an application running with the same privileges. In practical terms, that means you won’t be able to use the administrative database root user to connect from your PHP application. Setting a password for the root MySQL account works as a safeguard, in case the default authentication method is changed from unix_socket to password.

请注意,即使您在运行mysql_secure_installation脚本时定义了一个密码,也不需要提供密码即可以root用户身份进行连接。 这是因为MySQL管理用户的默认身份验证方法是unix_socket而不是password 。 即使最初看起来像是安全问题,它也使数据库服务器更加安全,因为唯一允许以root root用户身份登录的用户是具有sudo特权的系统用户,这些用户从控制台或通过以相同的特权。 实际上,这意味着您将无法使用管理数据库用户从PHP应用程序进行连接。 在默认身份验证方法从unix_socket更改为password情况下,为MySQL 帐户设置密码是一种保护措施。

For increased security, it’s best to have dedicated user accounts with less expansive privileges set up for every database, especially if you plan on having multiple databases hosted on your server.

为了提高安全性,最好为每个数据库设置专用的用户帐户,并为其设置较少的扩展特权,尤其是如果您计划在服务器上托管多个数据库时。

Note: At the time of this writing, the native MySQL PHP library mysqlnd doesn’t support caching_sha2_authentication, the default authentication method for MySQL 8. For that reason, when creating database users for PHP applications on MySQL 8, you’ll need to make sure they’re configured to use mysql_native_password instead. We’ll demonstrate how to do that in Step 6.

注意:在撰写本文时,本机MySQL PHP库mysqlnd 不支持 caching_sha2_authentication ,这是MySQL 8的默认身份验证方法。因此,在MySQL 8上为PHP应用程序创建数据库用户时,您需要确保将它们配置为使用mysql_native_password代替。 我们将在步骤6中演示如何做到这一点。

Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LEMP stack.

您MySQL服务器现已安装并保护。 接下来,我们将安装PHP,这是LEMP堆栈中的最后一个组件。

步骤3 –安装PHP (Step 3 – Installing PHP)

You have Nginx installed to serve your content and MySQL installed to store and manage your data. Now you can install PHP to process code and generate dynamic content for the web server.

您已经安装了Nginx来提供内容,并安装了MySQL以存储和管理数据。 现在,您可以安装PHP来处理代码并为Web服务器生成动态内容。

While Apache embeds the PHP interpreter in each request, Nginx requires an external program to handle PHP processing and act as a bridge between the PHP interpreter itself and the web server. This allows for a better overall performance in most PHP-based websites, but it requires additional configuration. You’ll need to install php-fpm, which stands for “PHP fastCGI process manager”, and tell Nginx to pass PHP requests to this software for processing. Additionally, you’ll need php-mysql, a PHP module that allows PHP to communicate with MySQL-based databases. Core PHP packages will automatically be installed as dependencies.

虽然Apache在每个请求中都嵌入了PHP解释器,但Nginx需要一个外部程序来处理PHP处理并充当PHP解释器本身和Web服务器之间的桥梁。 这可以在大多数基于PHP的网站中提供更好的整体性能,但是需要其他配置。 您需要安装php-fpm ,它代表“ PHP fastCGI进程管理器”,并告诉Nginx将PHP请求传递给该软件进行处理。 此外,您将需要php-mysql ,这是一个允许PHP与基于MySQL的数据库进行通信PHP模块。 核心PHP软件包将自动安装为依赖项。

To install the php-fpm and php-mysql packages, run:

要安装php-fpmphp-mysql软件包,请运行:

  • sudo apt install php-fpm php-mysql

    须藤apt安装php-fpm php-mysql

When prompted, type Y and ENTER to confirm installation.

出现提示时,键入YENTER确认安装。

You now have your PHP components installed. Next, you’ll configure Nginx to use them.

现在,您已经安装了PHP组件。 接下来,您将配置Nginx以使用它们。

第4步-配置Nginx使用PHP处理器 (Step 4 — Configuring Nginx to Use the PHP Processor)

When using the Nginx web server, we can create server blocks (similar to virtual hosts in Apache) to encapsulate configuration details and host more than one domain on a single server. In this guide, we’ll use your_domain as an example domain name. To learn more about setting up a domain name with DigitalOcean, see our introduction to DigitalOcean DNS.

使用Nginx Web服务器时,我们可以创建服务器块 (类似于Apache中的虚拟主机)来封装配置详细信息,并在一台服务器上托管多个域。 在本指南中,我们将使用your_domain作为示例域名。 要了解有关使用DigitalOcean设置域名的更多信息,请参阅DigitalOcean DNS简介

On Ubuntu 20.04, Nginx has one server block enabled by default and is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become difficult to manage if you are hosting multiple sites. Instead of modifying /var/www/html, we’ll create a directory structure within /var/www for the your_domain website, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.

在Ubuntu 20.04上,Nginx默认情况下启用了一个服务器块,并将其配置为提供/var/www/html目录中的文档。 尽管这对于单个站点非常有效,但是如果您托管多个站点,则可能变得难以管理。 我们将在/var/wwwyour_domain网站创建目录结构,而不是修改/var/www/html ,如果客户请求未得到响应,则将/var/www/html保留为默认目录以供使用匹配其他任何网站。

Create the root web directory for your_domain as follows:

your_domain创建根Web目录,如下所示:

  • sudo mkdir /var/www/your_domain

    须藤mkdir / var / www / your_domain

Next, assign ownership of the directory with the $USER environment variable, which will reference your current system user:

接下来,使用$ USER环境变量分配目录的所有权,该变量将引用您当前的系统用户:

  • sudo chown -R $USER:$USER /var/www/your_domain

    须藤chown -R $ USER:$ USER / var / www / your_domain

Then, open a new configuration file in Nginx’s sites-available directory using your preferred command-line editor. Here, we’ll use nano:

然后,使用首选的命令行编辑器在Nginx的sites-available目录中打开一个新的配置文件。 在这里,我们将使用nano

  • sudo nano /etc/nginx/sites-available/your_domain

    须藤纳米/ etc / nginx / sites-available / your_domain

This will create a new blank file. Paste in the following bare-bones configuration:

这将创建一个新的空白文件。 粘贴以下基本配置:

/etc/nginx/sites-available/your_domain
/ etc / nginx / sites-available / your_domain
server {
    listen 80;
    server_name your_domain www.your_domain;
    root /var/www/your_domain;

    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
     }

    location ~ /\.ht {
        deny all;
    }

}

Here’s what each of these directives and location blocks do:

这些指令和位置块的作用如下:

  • listen — Defines what port Nginx will listen on. In this case, it will listen on port 80, the default port for HTTP.

    listen —定义Nginx将监听的端口。 在这种情况下,它将监听端口80 (HTTP的默认端口)。

  • root — Defines the document root where the files served by this website are stored.

    root -定义文档根目录,该根目录用于存储此网站提供的文件。

  • index — Defines in which order Nginx will prioritize index files for this website. It is a common practice to list index.html files with a higher precedence than index.php files to allow for quickly setting up a maintenance landing page in PHP applications. You can adjust these settings to better suit your application needs.

    index —定义Nginx将对该网站的索引文件进行优先排序的顺序。 通常的做法是列出优先于index.php文件的index.html文件,以允许在PHP应用程序中快速设置维护登录页面。 您可以调整这些设置以更好地满足您的应用程序需求。

  • server_name — Defines which domain names and/or IP addresses this server block should respond for. Point this directive to your server’s domain name or public IP address.

    server_name定义此服务器块应响应的域名和/或IP地址。 将此指令指向服务器的域名或公共IP地址。

  • location / — The first location block includes a try_files directive, which checks for the existence of files or directories matching a URI request. If Nginx cannot find the appropriate resource, it will return a 404 error.

    location / —第一个location块包含try_files指令,该指令检查是否存在与URI请求匹配的文件或目录。 如果Nginx找不到合适的资源,它将返回404错误。

  • location ~ \.php$ — This location block handles the actual PHP processing by pointing Nginx to the fastcgi-php.conf configuration file and the php7.4-fpm.sock file, which declares what socket is associated with php-fpm.

    location ~ \.php$ —此位置块通过将Nginx指向fastcgi-php.conf配置文件和php7.4-fpm.sock文件来处理实际PHP处理,该文件声明了与php-fpm关联的套接字。

  • location ~ /\.ht — The last location block deals with .htaccess files, which Nginx does not process. By adding the deny all directive, if any .htaccess files happen to find their way into the document root ,they will not be served to visitors.

    location ~ /\.ht —最后一个位置块处理.htaccess文件,Nginx不会处理。 通过添加deny all指令,如果任何.htaccess文件碰巧进入文档根目录,它们将不会提供给访问者。

When you’re done editing, save and close the file. If you’re using nano, you can do so by typing CTRL+X and then y and ENTER to confirm.

完成编辑后,保存并关闭文件。 如果您使用的是nano ,则可以通过键入CTRL+X ,然后输入yENTER进行确认。

Activate your configuration by linking to the config file from Nginx’s sites-enabled directory:

通过链接到Nginx sites-enabled目录中的配置文件来激活您的配置:

  • sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

    sudo ln -s / etc / nginx / sites-available / your_domain / etc / nginx / sites-enabled /

This will tell Nginx to use the configuration next time it is reloaded. You can test your configuration for syntax errors by typing:

这将告诉Nginx在下次重新加载时使用配置。 您可以通过键入以下内容来测试配置中的语法错误:

  • sudo nginx -t

    须藤Nginx -t

If any errors are reported, go back to your configuration file to review its contents before continuing.

如果报告了任何错误,请在继续操作之前返回到配置文件以检查其内容。

When you are ready, reload Nginx to apply the changes:

准备就绪后,重新加载Nginx以应用更改:

  • sudo systemctl reload nginx

    须藤systemctl重新加载nginx

Your new website is now active, but the web root /var/www/your_domain is still empty. Create an index.html file in that location so that we can test that your new server block works as expected:

您的新网站现在处于活动状态,但是Web根目录/var/www/ your_domain仍然为空。 在该位置创建一个index.html文件,以便我们可以测试您的新服务器块是否按预期工作:

  • nano /var/www/your_domain/index.html

    纳米/ var / www / your_domain /index.html

Include the following content in this file:

在此文件中包括以下内容:

/var/www/your_domain/index.html
/var/www/your_domain/index.html
<html>
  <head>
    <title>your_domain website</title>
  </head>
  <body>
    <h1>Hello World!</h1>

    <p>This is the landing page of <strong>your_domain</strong>.</p>
  </body>
</html>

Now go to your browser and access your server’s domain name or IP address, as listed within the server_name directive in your server block configuration file:

现在转到浏览器并访问服务器的域名或IP地址,如服务器块配置文件中server_name指令中列出的那样:

http://server_domain_or_IP

You’ll see a page like this:

您会看到这样的页面:

If you see this page, it means your Nginx server block is working as expected.

如果看到此页面,则表明您的Nginx服务器块正在按预期工作。

You can leave this file in place as a temporary landing page for your application until you set up an index.php file to replace it. Once you do that, remember to remove or rename the index.html file from your document root, as it would take precedence over an index.php file by default.

您可以将该文件保留为应用程序的临时登录页面,直到您设置一个index.php文件来替换它为止。 完成此操作后,请记住从文档根目录中删除或重命名index.html文件,因为默认情况下它将优先于index.php文件。

Your LEMP stack is now fully configured. In the next step, we’ll create a PHP script to test that Nginx is in fact able to handle .php files within your newly configured website.

您的LEMP堆栈现已完全配置。 在下一步中,我们将创建一个PHP脚本来测试Nginx实际上是否能够处理您新配置的网站中的.php文件。

第5步–使用Nginx测试PHP (Step 5 –Testing PHP with Nginx)

Your LEMP stack should now be completely set up. You can test it to validate that Nginx can correctly hand .php files off to your PHP processor.

您的LEMP堆栈现在应该已完全设置。 您可以对其进行测试,以验证Nginx是否可以将.php文件正确地传递给您PHP处理器。

You can do this by creating a test PHP file in your document root. Open a new file called info.php within your document root in your text editor:

您可以通过在文档根目录中创建一个测试PHP文件来实现。 在文本编辑器的文档根目录中打开一个名为info.php的新文件:

  • nano /var/www/your_domain/info.php

    纳米/ var / www / your_domain /info.php

Type or paste the following lines into the new file. This is valid PHP code that will return information about your server:

将以下行键入或粘贴到新文件中。 这是有效PHP代码,它将返回有关您的服务器的信息:

/var/www/your_domain/info.php
/var/www/your_domain/info.php
<?php
phpinfo();

When you are finished, save and close the file by typing CTRL+X and then y and ENTER to confirm.

完成后,通过键入CTRL + X ,然后按yENTER进行保存并关闭文件。

You can now access this page in your web browser by visiting the domain name or public IP address you’ve set up in your Nginx configuration file, followed by /info.php:

现在,您可以在Web浏览器中访问此页面,方法是访问在Nginx配置文件中设置的域名或公共IP地址,然后/info.php

http://server_domain_or_IP/info.php

You will see a web page containing detailed information about your server:

您将看到一个包含有关服务器的详细信息的网页:

After checking the relevant information about your PHP server through that page, it’s best to remove the file you created as it contains sensitive information about your PHP environment and your Ubuntu server. You can use rm to remove that file:

通过该页面检查有关PHP服务器的相关信息后,最好删除您创建的文件,因为该文件包含有关PHP环境和Ubuntu服务器的敏感信息。 您可以使用rm删除该文件:

  • sudo rm /var/www/your_domain/info.php

    须藤rm / var / www / your_domain /info.php

You can always regenerate this file if you need it later.

如果以后需要,可以随时重新生成该文件。

第6步-从PHP测试数据库连接(可选) (Step 6 — Testing Database Connection from PHP (Optional))

If you want to test whether PHP is able to connect to MySQL and execute database queries, you can create a test table with dummy data and query for its contents from a PHP script. Before we can do that, we need to create a test database and a new MySQL user properly configured to access it.

如果要测试PHP是否能够连接到MySQL并执行数据库查询,则可以创建带有伪数据的测试表,并从PHP脚本中查询其内容。 在此之前,我们需要创建一个测试数据库和一个正确配置为可以访问它的新MySQL用户。

At the time of this writing, the native MySQL PHP library mysqlnd doesn’t support caching_sha2_authentication, the default authentication method for MySQL 8. We’ll need to create a new user with the mysql_native_password authentication method in order to be able to connect to the MySQL database from PHP.

在撰写本文时,本机MySQL PHP库mysqlnd 不支持 caching_sha2_authentication ,这是MySQL 8的默认身份验证方法。我们需要使用mysql_native_password身份验证方法创建一个新用户,以便能够连接到PHPMySQL数据库。

We’ll create a database named example_database and a user named example_user, but you can replace these names with different values.

我们将创建一个名为example_database数据库和用户名为example_user,但你可以用不同的值替换这些名称。

First, connect to the MySQL console using the root account:

首先,使用root帐户连接到MySQL控制台:

  • sudo mysql

    须藤MySQL

To create a new database, run the following command from your MySQL console:

要创建新数据库,请从MySQL控制台运行以下命令:

  • CREATE DATABASE example_database;

    创建数据库example_database ;

Now you can create a new user and grant them full privileges on the custom database you’ve just created.

现在,您可以创建一个新用户,并向他们授予您刚创建的自定义数据库的全部特权。

The following command creates a new user named example_user, using mysql_native_password as default authentication method. We’re defining this user’s password as password, but you should replace this value with a secure password of your own choosing.

以下命令使用mysql_native_password作为默认身份验证方法创建一个名为example_user的新用户。 我们将此用户的密码定义为password ,但是您应使用自己选择的安全密码替换此值。

  • CREATE USER 'example_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';

    创建用户' example_user '@'%'用mysql_native_password标识' 密码 ';

Now we need to give this user permission over the example_database database:

现在,我们需要授予该用户对example_database数据库的权限:

  • GRANT ALL ON example_database.* TO 'example_user'@'%';

    全部授予example_database。* TO'example_user'@'%';

This will give the example_user user full privileges over the example_database database, while preventing this user from creating or modifying other databases on your server.

这将为example_user用户提供对example_database数据库的完全特权,同时阻止该用户在服务器上创建或修改其他数据库。

Now exit the MySQL shell with:

现在使用以下命令退出MySQL Shell:

  • exit

    出口

You can test if the new user has the proper permissions by logging in to the MySQL console again, this time using the custom user credentials:

您可以使用自定义用户凭据再次登录到MySQL控制台,以测试新用户是否具有适当的权限:

  • mysql -u example_user -p

    mysql -u example_user -p

Notice the -p flag in this command, which will prompt you for the password used when creating the example_user user. After logging in to the MySQL console, confirm that you have access to the example_database database:

请注意此命令中的-p标志,它将提示您输入创建example_user用户时使用的密码。 登录到MySQL控制台后,确认您有权访问example_database数据库:

  • SHOW DATABASES;

    显示数据库;

This will give you the following output:

这将为您提供以下输出:


   
   
Output
+--------------------+ | Database | +--------------------+ | example_database | | information_schema | +--------------------+ 2 rows in set (0.000 sec)

Next, we’ll create a test table named todo_list. From the MySQL console, run the following statement:

接下来,我们将创建一个名为todo_list的测试表。 在MySQL控制台中,运行以下语句:

  • CREATE TABLE example_database.todo_list (

    创建表example_database 。 todo_list (

  • item_id INT AUTO_INCREMENT,

    item_id INT AUTO_INCREMENT,
  • content VARCHAR(255),

    内容VARCHAR(255),
  • PRIMARY KEY(item_id)

    主键(item_id)
  • );

    );

Insert a few rows of content in the test table. You might want to repeat the next command a few times, using different values:

在测试表中插入几行内容。 您可能需要使用不同的值重复执行下一条命令几次:

  • INSERT INTO example_database.todo_list (content) VALUES ("My first important item");

    插入INTO example_database 。 todo_list (内容)VALUES(“ 我的第一个重要项目 ”);

To confirm that the data was successfully saved to your table, run:

要确认数据已成功保存到表中,请运行:

  • SELECT * FROM example_database.todo_list;

    SELECT * FROM example_database 。 todo_list ;

You’ll see the following output:

您将看到以下输出:


   
   
Output
+---------+--------------------------+ | item_id | content | +---------+--------------------------+ | 1 | My first important item | | 2 | My second important item | | 3 | My third important item | | 4 | and this one more thing | +---------+--------------------------+ 4 rows in set (0.000 sec)

After confirming that you have valid data in your test table, you can exit the MySQL console:

确认测试表中有有效数据后,可以退出MySQL控制台:

  • exit

    出口

Now you can create the PHP script that will connect to MySQL and query for your content. Create a new PHP file in your custom web root directory using your preferred editor. We’ll use nano for that:

现在,您可以创建将连接到MySQL并查询您的内容PHP脚本。 使用首选编辑器在自定义Web根目录中创建一个新PHP文件。 我们将为此使用nano

  • nano /var/www/your_domain/todo_list.php

    纳米/ var / www / your_domain / todo_list.php

The following PHP script connects to the MySQL database and queries for the content of the todo_list table, exhibiting the results in a list. If there’s a problem with the database connection, it will throw an exception. Copy this content into your todo_list.php script:

以下PHP脚本连接到MySQL数据库,并查询todo_list表的内容,并将结果显示在列表中。 如果数据库连接有问题,它将引发异常。 将此内容复制到您的todo_list.php脚本中:

/var/www/your_domain/todo_list.php
/var/www/your_domain/todo_list.php
<?php
$user = "example_user";
$password = "password";
$database = "example_database";
$table = "todo_list";

try {
  $db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
  echo "<h2>TODO</h2><ol>"; 
  foreach($db->query("SELECT content FROM $table") as $row) {
    echo "<li>" . $row['content'] . "</li>";
  }
  echo "</ol>";
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

Save and close the file when you’re done editing.

完成编辑后,保存并关闭文件。

You can now access this page in your web browser by visiting the domain name or public IP address configured for your website, followed by /todo_list.php:

现在,您可以在Web浏览器中访问此页面,方法是访问为网站配置的域名或公共IP地址,然后访问/todo_list.php

http://server_domain_or_IP/todo_list.php

You should see a page like this, showing the content you’ve inserted in your test table:

您应该看到这样的页面,显示您已插入测试表中的内容:

That means your PHP environment is ready to connect and interact with your MySQL server.

这意味着您PHP环境已准备就绪,可以连接到MySQL服务器并与之交互。

结论 (Conclusion)

In this guide, we’ve built a flexible foundation for serving PHP websites and applications to your visitors, using Nginx as web server and MySQL as database system.

在本指南中,我们使用Nginx作为Web服务器和MySQL作为数据库系统,为为访问者提供PHP网站和应用程序奠定了灵活的基础。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-20-04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值