建站流程

发布于 2024-03-09  66 次阅读


How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu 20.04

English

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.

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.

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.

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.

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:

  1. sudoapt update
  2. sudoapt install 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.

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:

  1. sudoufw app list

 

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.

Enable this by typing:

  1. sudoufw allow 'Nginx HTTP'

 

You can verify the change by running:

  1. sudoufw status

 

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

Output

Status: active

 

To                         Action      From

--                         ------      ----

OpenSSH                    ALLOW       AnywhereNginx 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.

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:

  1. ipaddr show 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.

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

  1. curl-4com

 

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

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.

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.

Again, use apt to acquire and install this software:

  1. sudoapt install mysql-server

 

When prompted, confirm installation by typing Y, and then 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:

  1. sudomysql_secure_installation

 

This will ask if you want to configure the 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.

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

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.

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.

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:

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.

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

  1. sudomysql

 

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:

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:

  1. 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.

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.

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

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.

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.

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

  1. sudoapt install php-fpm php-mysql

 

When prompted, type Y and ENTER to confirm installation.

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

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.

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.

Create the root web directory for your_domain as follows:

  1. sudomkdir /var/www/your_domain

 

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

  1. sudochown -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:

  1. sudonano /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

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.
  • root— Defines the document root where the files served by this website are stored.
  • index— Defines in which order Nginx will prioritize index files for this website. It is a common practice to list 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.
  • 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.
  • 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 ~ \.php$— This location block handles the actual PHP processing by pointing Nginx to the fastcgi-php.conf configuration file and the 4-fpm.sock file, which declares what socket is associated with 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.

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.

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

  1. sudoln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

 

Then, unlink the default configuration file from the /sites-enabled/ directory:

  1. sudounlink /etc/nginx/sites-enabled/default

 

Note: If you ever need to restore the default configuration, you can do so by recreating the symbolic link, like this:

  1. sudoln -s /etc/nginx/sites-available/default /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:

  1. sudonginx -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:

  1. sudosystemctl reload 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:

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

 

Include the following content in this file:

/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:

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.

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.

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.

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.

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:

  1. nano/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:

/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.

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:

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:

  1. sudorm /var/www/your_domain/info.php

 

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

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.

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.

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

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

  1. sudomysql

 

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

  1. CREATE 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.

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

 

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

  1. GRANT ALL ON 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.

Now exit the MySQL shell with:

  1. 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:

  1. mysql -uexample_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:

  1. 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:

  1. CREATE TABLE example_database.todo_list (
  2. item_id INT AUTO_INCREMENT,
  3. content VARCHAR(255),
  4. PRIMARY KEY(item_id)
  5. );

 

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

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

 

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

  1. 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:

  1. 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:

  1. nano/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:

/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:

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.

Step 1 — Creating a MySQL Database and User for WordPress

WordPress uses MySQL to manage and store site and user information. Although you already have MySQL installed, let’s create a database and a user for WordPress to use.

To get started, log in to the MySQL root (administrative) account. If MySQL is configured to use the auth_socket authentication plugin (which is default), you can log in to the MySQL administrative account using sudo:

  1. sudomysql

 

If you have changed the authentication method to use a password for the MySQL root account, use the following command instead:

  1. mysql -uroot -p

 

You will be prompted for the password you set for the MySQL root account.

Once logged in, create a separate database that WordPress can control. You can call this whatever you would like, but we will be using wordpress in this guide to keep it simple. You can create a database for WordPress by entering:

  1. CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

 

Note: Every MySQL statement must end in a semi-colon (;). If you’ve encountered an error, check to make sure the semicolon is present.

Next, let’s create a separate MySQL user account that we will use exclusively to operate on our new database. Creating single-purpose databases and accounts is a good idea from a management and security standpoint. We’ll use the name wordpressuser in this guide — feel free to change this if you’d like.

In the following command, you are going to create an account, set a password, and grant access to the database you created. Remember to choose a strong password here:

  1. CREATE USER'wordpressuser'@'localhost' IDENTIFIED BY 'password';
  2. GRANT ALL ON wordpress.* TO 'wordpressuser'@'localhost';

 

You now have a database and user account, each made specifically for WordPress.

With the database tasks complete, let’s exit out of MySQL by typing:

  1. EXIT;

 

The MySQL session will exit, returning you to the regular Linux shell.

Step 2 — Installing Additional PHP Extensions

When setting up the LEMP stack, it required a very minimal set of extensions to get PHP to communicate with MySQL. WordPress and many of its plugins leverage additional PHP extensions, and you’ll use a few more in this tutorial.

Let’s download and install some of the most popular PHP extensions for use with WordPress by typing:

  1. sudoapt update

 

  1. sudoapt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip

 

Note: Each WordPress plugin has its own set of requirements. Some may require additional PHP extension packages to be installed. Check your plugin documentation to discover its PHP requirements. If they are available, they can be installed with apt as demonstrated above.

When you are finished installing the extensions, restart the PHP-FPM process so that the running PHP processor can leverage the newly installed features:

  1. sudosystemctl restart php7.4-fpm

 

You now have all of the PHP extensions needed, installed on the server.

Step 3 — Configuring Nginx

Next, let’s make a few adjustments to our Nginx server block files. Based on the prerequisite tutorials, you should have a configuration file for your site in the /etc/nginx/sites-available/ directory configured to respond to your server’s domain name or IP address and protected by a TLS/SSL certificate. We’ll use /etc/nginx/sites-available/wordpress as an example here, but you should substitute the path to your configuration file where appropriate.

Additionally, we will use /var/www/wordpress as the root directory of our WordPress install in this guide. Again, you should use the web root specified in your own configuration.

Note: It’s possible you are using the /etc/nginx/sites-available/default default configuration (with /var/www/html as your web root). This is fine to use if you’re only going to host one website on this server. If not, it’s best to split the necessary configuration into logical chunks, one file per site.

Open your site’s server block file with sudo privileges to begin:

  1. sudonano /etc/nginx/sites-available/wordpress

 

Within the main server block, let’s add a few location blocks.

Start by creating exact-matching location blocks for requests to /favicon.ico and /robots.txt, both of which you do not want to log requests for.

Use a regular expression location to match any requests for static files. We will again turn off the logging for these requests and will mark them as highly cacheable, since these are typically expensive resources to serve. You can adjust this static files list to contain any other file extensions your site may use:

/etc/nginx/sites-available/wordpress

server {

. . .

 

location = /favicon.ico { log_not_found off; access_log off; }

location = /robots.txt { log_not_found off; access_log off; allow all; }

location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {

expires max;

log_not_found off;

}

. . .

}

Inside of the existing location / block, let’s adjust the try_files list. Comment out the default setting by prepending the line with a pound sign (#) and then add the highlighted line. This way, instead of returning a 404 error as the default option, control is passed to the index.php file with the request arguments.

This should look something like this:

/etc/nginx/sites-available/wordpress

server {

. . .

location / {

#try_files $uri $uri/ =404;

try_files $uri $uri/ /index.php$is_args$args;

}

. . .

}

When you are finished, save and close the file.

Now, let’s check our configuration for syntax errors by typing:

  1. sudonginx -t

 

If no errors were reported, reload Nginx by typing:

  1. sudosystemctl reload nginx

 

Next, let’s download and set up WordPress.

Step 4 — Downloading WordPress

Now that your server software is configured, let’s download and set up WordPress. For security reasons, it is always recommended to get the latest version of WordPress directly from the project’s website.

Change into a writable directory and then download the compressed release by typing:

  1. cd/tmp

 

This changes your directory to the temporary folder. Then, enter the following command to download the latest version of WordPress in a compressed file:

  1. curl-LO https://wordpress.org/latest.tar.gz

 

Note: The -LO flag is used to get directly to the source of the compressed file. -L ensures that fetching the file is successful in the case of redirects, and -O writes the output of our remote file with a local file that has the same name. To learn more about curl commands, visit How to Download Files with cURL

Extract the compressed file to create the WordPress directory structure:

  1. tarxzvf latest.tar.gz

 

You will be moving these files into our document root momentarily, but before you do, let’s copy over the sample configuration file to the filename that WordPress actually reads:

  1. cp/tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

 

Now, let’s copy the entire contents of the directory into our document root. We’re using the -a flag to make sure our permissions are maintained, and a dot at the end of our source directory to indicate that everything within the directory should be copied (including hidden files):

  1. sudocp -a /tmp/wordpress/. /var/www/wordpress

 

Now that our files are in place, you’ll assign ownership to the www-data user and group. This is the user and group that Nginx runs as, and Nginx will need to be able to read and write WordPress files in order to serve the website and perform automatic updates:

  1. sudochown -R www-data:www-data /var/www/wordpress

 

Files are now in the server’s document root and have the correct ownership, but you still need to complete some additional configuration.

Step 5 — Setting up the WordPress Configuration File

Next, let’s make some changes to the main WordPress configuration file.

When you open the file, you’ll start by adjusting some secret keys to provide some security for our installation. WordPress provides a secure generator for these values so that you don’t have to come up with values on your own. These are only used internally, so it won’t hurt usability to have complex, secure values here.

To grab secure values from the WordPress secret key generator, type:

  1. curl-s https://api.wordpress.org/secret-key/1.1/salt/

 

You will get back unique values that look something like this:

Warning: It is important that you request unique values each time. Do NOT copy the values shown below!

Output

define('AUTH_KEY',         '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H');

define('SECURE_AUTH_KEY',  'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3');

define('LOGGED_IN_KEY',    'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88');

define('NONCE_KEY',        'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g');

define('AUTH_SALT',        'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES  07VC*Lj*lD&?3w!BT#-');

define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY');

define('LOGGED_IN_SALT',   'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|');

define('NONCE_SALT',       'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

These are configuration lines that you can paste directly in your configuration file to set secure keys. Copy the output you received now.

Now, open the WordPress configuration file:

  1. sudonano /var/www/wordpress/wp-config.php

 

Find the section that contains the dummy values for those settings. It will look something like this:

/var/www/wordpress/wp-config.php

. . .

 

define('AUTH_KEY',         'put your unique phrase here');

define('SECURE_AUTH_KEY',  'put your unique phrase here');

define('LOGGED_IN_KEY',    'put your unique phrase here');

define('NONCE_KEY',        'put your unique phrase here');

define('AUTH_SALT',        'put your unique phrase here');

define('SECURE_AUTH_SALT', 'put your unique phrase here');

define('LOGGED_IN_SALT',   'put your unique phrase here');

define('NONCE_SALT',       'put your unique phrase here');

 

. . .

Delete those lines and paste in the values you copied from the command line:

/var/www/wordpress/wp-config.php

. . .

 

define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');

define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');

define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');

define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');

define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');

define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');

define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');

define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');

 

. . .

Next, let’s modify some of the database connection settings at the beginning of the file. You’ll have to adjust the database name, the database user, and the associated password that was configured within MySQL.

The other change you should make is to set the method that WordPress uses to write to the filesystem. Since you’ve given the web server permission to write where it needs to, you can explicitly set the filesystem method to “direct”. Failure to set this with our current settings would result in WordPress prompting for FTP credentials when we perform some actions. Add this setting below the database connection settings, or anywhere else in the file:

/var/www/wordpress/wp-config.php

. . .

 

define( 'DB_NAME', 'wordpress' );

 

/** MySQL database username */

define( 'DB_USER', 'wordpressuser' );

 

/** MySQL database password */

define( 'DB_PASSWORD', 'password' );

 

. . .

define( 'FS_METHOD', 'direct' );

Save and close the file when you’re done.

Step 6 — Completing the Installation Through the Web Interface

Now that the server configuration is complete, you can finish up the installation through WordPress’ web interface.

In your web browser, navigate to your server’s domain name or public IP address:

http://server_domain_or_IP/wordpress

Select the language you would like to use:

 

Next, you will come to the main setup page.

Select a name for your WordPress site and choose a username (it is recommended not to choose something like “admin” for security purposes). A strong password is generated automatically. Save this password or select an alternative strong password.

Enter your email address and select whether you want to discourage search engines from indexing your site:

 

When you click ahead, you will be taken to a page that prompts you to log in:

 

Once you log in, you will be taken to the WordPress administration dashboard:

 

 

Published on April 30, 2020 · Updated on February 2, 2021

By Erika Heidi

Praise seniors to teach us

 

简要说明: (建议查看上面教程,下面说明只为快速查询,解释不完全)

提前安装mysql php-fpm php-mysql nginx

 

 

mysql 安装和使用

----------安装 和使用--

1.更新包 sudo apt update

2.安装 sudo apt install mariadb-server

在安装过程中,你将被提示设置root用户的密码。请设置一个强密码,并确保记住它。 未提示

3.启动并启用服务

sudo systemctl start mariadb

sudo systemctl enable mariadb

  1. 配置MySQL或MariaDB安全性:

sudo mysql_secure_installation

  1. 连接到MySQL或MariaDB:

mysql -u root -p

 

 

mysql -u root -p

输入密码 root

 

SHOW DATABASES;

use databasename

 

----------for wordpress--

 

  1. 创建wordpress使用的数据库

CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

 

2.为wordpress创建用户

CREATE USER 'worduser'@'localhost' IDENTIFIED BY 'wordpress';

 

GRANT ALL ON wordpress.* TO 'worduser'@'localhost';

 

----------------------------------------------------------

安装php及扩展

安装php

sudo apt update

sudo apt install php-fpm php-mysql

安装扩展

sudo apt install php-curl php-gd php-intl php-mbstring php-soap php-xml php-xmlrpc php-zip

 

完成安装扩展后,重新启动 PHP-FPM 进程,以便运行的 PHP 处理器可以利用新安装的功能:

sudo systemctl restart php7.4-fpm

 

----------------------------------------------------------

安装及配置nginx

安装

sudo apt update

sudo apt install nginx-full  (包含steam模块更方便之后分流)

设置防火墙

sudo ufw app list

sudo ufw allow 'Nginx HTTP'

sudo ufw status

查看包含Nginx Http 即为成功

 

查看主机IP

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

curl -4 icanhazip.com

http://server_domain_or_IP

配置nginx for wordpress

 

/var/www/wordpress 新建目录

vi /etc/nginx/sites_available/nginx_wp.conf

进入之后按i 看底部变成insert 之后

添加以下代码

-------------begin------------------

server {

listen 80;

server_name your_domain www.your_domain;

root /var/www/wordpress;

 

index index.html index.htm index.php;

 

location / {

#try_files $uri $uri/ =404;

try_files $uri $uri/ /index.php$is_args$args;

 

}

location ~ \.php$ {

include snippets/fastcgi-php.conf;

fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

}

 

location ~ /\.ht {

deny all;

}

location = /favicon.ico { log_not_found off; access_log off; }

location = /robots.txt { log_not_found off; access_log off; allow all; }

location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {

expires max;

log_not_found off;

}

}

------------end------------------

将配置文件链接

sudo ln -s /etc/nginx/sites-available/nginx_wp.conf /etc/nginx/sites-enabled/

解除原本链接

sudo unlink /etc/nginx/sites-enabled/default

 

查看是否配置正确

sudo nginx -t

重新加载

sudo systemctl reload nginx

sudo systemctl restart nginx

 

-----index.html测试nginx用,成功之后删除----

在/var/www/wordpress 目录下新建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>

访问个人网站 (输入域名或者ip)

http://server_domain_or_IP

出现下面页面即为正确

 

----测试php是否可用----

在/var/www/wordpress 目录下新建info.php文件

添加

<?php

phpinfo();

?>

访问 http://域名/info.php

http://server_domain_or_IP/info.php

 

出现详细信息即为正确

---------------------------------------------

第 4 步 — 下载 WordPress

cd /tmp

下载压缩包

curl -LO https://wordpress.org/latest.tar.gz

解压

tar xzvf latest.tar.gz

创建配置文件

cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

复制到网站目录

sudo cp -a /tmp/wordpress/. /var/www/wordpress

修改所属用户和组

sudo chown -R www-data:www-data /var/www/wordpress

 

获取配置

curl -s https://api.wordpress.org/secret-key/1.1/salt/

记录显示的配置信息后将其替换wp-config.php文件中对应部分

形如

define('AUTH_KEY',         'put your unique phrase here');

define('SECURE_AUTH_KEY',  'put your unique phrase here');

define('LOGGED_IN_KEY',    'put your unique phrase here');

define('NONCE_KEY',        'put your unique phrase here');

define('AUTH_SALT',        'put your unique phrase here');

define('SECURE_AUTH_SALT', 'put your unique phrase here');

define('LOGGED_IN_SALT',   'put your unique phrase here');

define('NONCE_SALT',       'put your unique phrase here');

 

sudo vi /var/www/wordpress/wp-config.php

替换之后将数据源信息替换为我们为wordpress准备的数据库

define( 'DB_NAME', 'wordpress' );

 

/** MySQL database username */

define( 'DB_USER', 'wordpressuser' );

 

/** MySQL database password */

define( 'DB_PASSWORD', 'password' );

 

. . .

define( 'FS_METHOD', 'direct' );

搭建完成 访问 http://server_domain_or_IP/wordpress

进入wordpress配置个人网站