WordPress

WordPress 建站教程:Ubuntu20.04+Nginx+PHP 7.4+MySQL 搭建 WordPress 网站

保姆级 WordPress 建站教程,小白也可放心食用!

本教程将以 Ubuntu Server 20.04 LTS 64bit 操作系统为例,介绍如何从零开始搭建 WordPress;本文档默认使用 root 用户进行操作。

注:如果你还未购买服务器,建议先前往腾讯云或阿里云购买。

准备工作

  • Ubuntu 20.04
  • 远程连接工具
    • 如腾讯云/阿里云服务器控制台的网页版远程连接工具
    • 也可以使用 SSH 客户端程序(如 Windows 操作系统上的 PuTTY 或 macOS 自带的终端 App)

当你以 root 用户身份 SSH 登录到服务器后,即可开始安装下面的步骤操作:

安装 Nginx

Nginx 是一种特殊的计算机程序,通常被用来帮助网站运行更顺畅。你可以把它想象成一个交通警察,它帮助控制网站上的流量,确保信息能够快速而准确地传送给你的电脑,就像交通警察帮助控制交通流量一样。这使得网站更快速和稳定,就像道路上的交通流畅一样。

Nginx 是一个免费的开源网络服务器软件,它用来处理网络请求并分发网页、应用程序或其他网络资源给用户。它在互联网上广泛使用,能够提供高性能、可靠性和安全性,常被用来搭建网站、反向代理、负载均衡等网络服务。它的名字发音类似于 “engine X”,象征着它的高性能和效率。总之,Nginx 是一个帮助网站和应用程序顺利运行的重要软件工具。

执行以下命令安装 Nginx:

apt install nginx

上述命令执行完毕后,浏览器访问你的服务器公网 ip;若显示以下内容则证明安装成功:

Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.

Thank you for using nginx.

注:如果发现访问超时,请确保防火墙80端口已打开。

安装 PHP 及其拓展

PHP(Hypertext Preprocessor的缩写)是一种流行的服务器端脚本语言,用于开发动态网页和 Web 应用程序。PHP 允许开发人员在网页中嵌入代码,以便在服务器上执行各种任务,例如数据库操作、用户验证、表单处理等。它是一种开源语言,易于学习和使用,因此在 Web 开发领域非常流行。

简单来说,PHP 是一种用于创建交互性强、动态性高的网站和应用程序的编程语言,它可以与数据库和其他服务器端技术结合使用,使网站能够根据用户的需求实时生成内容。

执行以下命令安装PHP及其扩展:

apt install php-fpm php-mysql php-gd php-curl php-dom php-mbstring php-imagick php-zip

安装 MySQL

MySQL 是一种流行的开源数据库管理系统,它用于存储和管理数据。数据库是一个像电子文件夹一样的地方,可以保存各种信息,比如网站上的用户数据、文章内容、订单信息等等。

简单来说,你可以把 MySQL 想象成一个巨大的电子表格,可以存储大量数据,并且可以帮助程序员轻松地在其中查找、添加、删除和修改数据。许多网站和应用程序使用 MySQL 来存储和管理它们的数据,这使得它们能够有效地处理和组织大量信息。所以,MySQL 是一个帮助网站和应用程序管理数据的工具。

执行下面的命令安装 MySQL:

apt install mysql-server

安装完成后,接着执行:

mysql_secure_installation

如果显示:

Securing the MySQL server deployment.

Enter password for user root:

如果在安装的时候设置过 MySQL 数据库 root 密码,则输入密码后再按 Enter 键,否则直接按 Enter 键跳过即可。

接着安装程序将会询问是否需要设置验证密码组件:

VALIDATE PASSWORD COMPONENT 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 component?

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

输入 y 然后按下 Enter;随后需要设置密码强度校验政策。这里根据个人的密码强度选择输入对应数字后按回车键即可。随后根据提示设置好 root 密码。

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:

接下来,输入 y 然后按下 Enter,删除匿名用户:

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

Remove anonymous users? (Press y|Y for Yes, any other key for No) :

继续输入 y 然后按下 Enter,禁止 root 远程登录:

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

Disallow root login remotely? (Press y|Y for Yes, any other key for No) :

再次输入 y 然后按下 Enter,删除测试数据库:

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


Remove test database and access to it? (Press y|Y for Yes, any other key for No) :

输入 y 然后按下 Enter,立即重新加载权限:

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

Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

至此,数据库初始化设置完成。接下来,输入以下命令进入数据库:

mysql -uroot -p

输入前面设置的 root 密码,然后按下 Enter。如果出现如下则证明成功进入数据库:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.23-0ubuntu0.20.04.1 (Ubuntu)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

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>

创建一个名为 wordpress 的数据库:

CREATE DATABASE IF NOT EXISTS wordpress DEFAULT CHARACTER SET = utf8mb4 DEFAULT COLLATE = utf8mb4_general_ci;

创建一个数据库用户 wordpress 用来操作上面创建的 wordpress 数据库。你需要修改命令中的 {password} 为你自己的密码。

CREATE USER 'wordpress'@'localhost' IDENTIFIED BY '{password}';

授予用户 wordpress 拥有数据库 wordpress 的所有权限:

GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpress'@'localhost' WITH GRANT OPTION;

刷新权限:

FLUSH PRIVILEGES;

退出数据库:

exit

下载 WordPress 安装程序

WordPress 是一种流行的免费开源内容管理系统(CMS),用于创建和管理网站、博客和在线商店等各种类型的网站。它是一个用户友好的平台,允许人们在不需要编写复杂代码的情况下轻松创建和维护网站内容。

你可以将 WordPress 想象成一个虚拟的建筑工地,你可以选择不同的设计和功能来建立你的网站,就像选择房屋的外观和内部布局一样。你可以轻松添加和编辑文章、图片、视频和其他内容,而无需成为编程专家。

总之,WordPress 是一个强大而灵活的工具,让任何人都能够创建自己的网站,而不必担心复杂的技术细节。它被广泛用于互联网上的各种网站和博客,全球有约40%的网站由 WordPress 驱动。

下载最新版的WordPress中文版安装程序到路径 /var/www 中,下载文件命名为 wordpress.tar.gz:

curl https://cn.wordpress.org/latest-zh_CN.tar.gz -o /var/www/wordpress.tar.gz

进入 /var/www 文件夹:

cd /var/www

解压前面下载的 wordpress.tar.gz 到当前文件夹中:

tar -zxvf wordpress.tar.gz

修改文件夹用户组权限:

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

修改 Nginx 配置文件

Nginx 配置文件是 Nginx 服务器使用的文本文件,用于定义服务器的行为和设置。这些配置文件告诉 Nginx 如何处理传入的网络请求,包括哪些网站和应用程序应该响应请求,如何处理不同类型的请求,以及如何处理安全性和性能等方面的设置。

通常,Nginx 有一个主要的全局配置文件,通常位于 /etc/nginx/nginx.conf 或 /usr/local/nginx/conf/nginx.conf(具体位置根据安装方式而定)。此外,Nginx 可以包含多个虚拟主机(或服务器块)的配置文件,这些文件通常存储在 /etc/nginx/sites-available/ 或 /etc/nginx/conf.d/ 目录中,然后通过符号链接或包含语句包含到主配置文件中。

Nginx 配置文件使用简单的语法,包括指令和块,用于定义服务器的行为。例如,可以使用配置文件指令来指定监听的端口、服务器的根目录、日志文件的位置、SSL 证书的配置以及其他各种设置。

先复制一份默认配置,并将下面命令中的 {domain} 更换为你自己的域名。

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/{domain}.conf

然后使用 Vim 编辑器打开配置文件进行修改:

vi /etc/nginx/sites-available/{domain}.conf

注:如果提示 bash: vi: command not found. 则先通过下面的命令安装 Vim,安装完成后再执行前面的命令修改配置。

apt install vim

执行 vi /etc/nginx/sites-available/{domain}.conf 打开配置文件后,按下键盘的i键进入编辑状态,将配置修改成如下,修改好后按Esc退出编辑状态,最后按下:wq保存修改并关闭配置文件。

server {
  listen 80;
  listen [::]:80;
  root /var/www/wordpress;
  index index.php;
  server_name {you-domain};
  location / {
    try_files $uri $uri/ =404;
  }
  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
  }
}

注:如果没有使用域名,则无需修改配置文件内的 server_name 字段。其中配置文件内 fastcgi_pass 这一项中的 php7.4-fpm.sock 对应的是php-fpm版本。

本文安装的是 PHP 7.4,在修改配置时请记得替换成你们安装的版本。如果不确定自己安装的PHP是什么版本,可通过 php -v 命令查看服务器安装的对应PHP版本。

接下来,删除正在使用的默认配置:

rm /etc/nginx/sites-enabled/default

将修改好的配置加入到正在使用的配置中:

ln -s /etc/nginx/sites-available/{domain}.conf /etc/nginx/sites-enabled/

测试配置是否正确:

nginx -t

看到如下信息则代表配置成功:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重载配置以生效:

nginx -s reload

WordPress 5分钟安装程序

WordPress 5分钟安装程序是WordPress官方网站提供的一个简化安装过程的工具,旨在使用户能够快速轻松地在自己的网站服务器上安装WordPress。这个工具的名字虽然叫做”5分钟安装程序”,但实际上安装时间可能会因服务器配置和用户操作而有所不同。

回到浏览器访问服务器公网ip,将会看到WordPress欢迎页面。点击“下方现在就开始!”按钮继续。

在下一个界面中,将用户名修改为 wordpress,密码一栏填入刚才设置的数据库密码,然后点击提交即可。

随后,你将会看到 WordPress 成功安装的页面:


至此,你已成功在自己的服务器上部署了一个 WordPress 网站。

More Reading

Post navigation

2,188 Comments

  • Hmm is anyone else encountering problems with the images on this blog loading?

    I’m trying to find out if its a problem
    on my end or if it’s the blog. Any feedback would be greatly appreciated.

  • It’s amazing to pay a quick visit this website and reading the views of all friends on the topic of this article, while
    I am also eager of getting experience.

  • My coder is trying to persuade me to move to .net from
    PHP. I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am anxious about switching to another platform.
    I have heard fantastic things about blogengine.net.
    Is there a way I can transfer all my wordpress
    posts into it? Any help would be really appreciated!

  • You made some really good points there. I checked on the net to find out more
    about the issue and found most people will go along with your views on this web site.

  • I think what you published was very logical.
    However, what about this? suppose you composed a catchier title?

    I mean, I don’t wish to tell you how to run your blog, but suppose you added a post title to maybe get people’s attention? I mean WordPress 建站教程:Ubuntu20.04+Nginx+PHP 7.4+MySQL 搭建 WordPress 网站 – 小斌写字的地方 is a little plain.
    You might glance at Yahoo’s front page and note
    how they create news headlines to grab people to open the links.
    You might add a related video or a related pic or two to grab people excited about everything’ve written. Just my opinion, it could bring your
    website a little bit more interesting.

  • each time i used to read smaller articles that as well clear their motive,
    and that is also happening with this article which I am reading at this
    place.

  • I think that what you published was actually very logical.
    However, think on this, what if you added a little content?
    I am not saying your content isn’t good., however what if you added a post
    title to maybe get people’s attention? I mean WordPress 建站教程:Ubuntu20.04+Nginx+PHP
    7.4+MySQL 搭建 WordPress 网站 – 小斌写字的地方 is
    a little vanilla. You might glance at Yahoo’s home page and watch how they create article headlines to get viewers to open the links.

    You might add a video or a related picture or two to get readers excited about what you’ve written. In my opinion, it would make your
    blog a little bit more interesting.

  • Hello, Neat post. There’s a problem with your website in internet explorer,
    might check this? IE nonetheless is the marketplace chief and a good component of
    people will miss your great writing because of this problem.

  • I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish.
    nonetheless, you command get got an impatience over that you wish be delivering
    the following. unwell unquestionably come more formerly
    again since exactly the same nearly very often inside case you
    shield this increase.

  • Terrific work! That is the type of information that are supposed to be shared across the net.
    Shame on the seek engines for not positioning this put up higher!
    Come on over and consult with my web site . Thank you =)

  • Здорова, народ Брат снова сорвался Родственники не знают что делать Таблетки не помогают Короче, единственный кто реально помог — наркологическая помощь на дому в казани качественно Через пару часов человек пришёл в себя В общем, не потеряйте контакты — частная наркологическая помощь [url=https://zapoj.narkologicheskaya-pomoshh-v-kazani16.ru]частная наркологическая помощь[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  • Greetings! I know this is kinda off topic but I’d figured I’d ask.

    Would you be interested in exchanging links or maybe guest writing
    a blog post or vice-versa? My site addresses a lot of the same subjects as
    yours and I feel we could greatly benefit from each other.
    If you’re interested feel free to send me an email.
    I look forward to hearing from you! Great blog by the way!

  • Слушайте кто знает Близкий человек уже несколько дней в запое Соседи стучат в стену В больницу тащить страшно Короче, только это реально спасло — помощь нарколога на дому Через пару часов человек пришёл в себя В общем, телефон и цены тут — наркологическая помощь казань [url=https://czena.narkologicheskaya-pomoshh-v-kazani016.ru]https://czena.narkologicheskaya-pomoshh-v-kazani016.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  • I every time used to study post in news papers but now as I am a user of internet therefore from now I am using net
    for articles, thanks to web.

  • Казань, всем привет Отец не выходит из штопора Родственники не знают что делать Таблетки не помогают Короче, только это реально спасло — нарколог услуги цены адекватные Осмотрел и поставил капельницу В общем, вся инфа по ссылке — оказание наркологической помощи [url=https://kapelnicza.narkologicheskaya-pomoshh-v-kazani16.ru]оказание наркологической помощи[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  • Hey there! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months
    of hard work due to no back up. Do you have
    any methods to prevent hackers?

  • I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it
    for you? Plz respond as I’m looking to design my own blog
    and would like to know where u got this from. cheers

  • Hi there to all, how is the whole thing, I think every one is
    getting more from this web page, and your views are pleasant in support of new viewers.

  • Люди помогите советом Близкий человек уже несколько дней в запое Дети напуганы Таблетки не помогают Короче, только это реально спасло — помощь нарколога на дому анонимно Через пару часов человек пришёл в себя В общем, вся инфа по ссылке — врач нарколог на дом [url=https://lechenie.narkolog-na-dom-sankt-peterburg014.ru]врач нарколог на дом[/url] Не ждите пока станет хуже Перешлите тем кто в такой же ситуации

  • Люди подскажите Ситуация критическая Дети напуганы Нужен врач прямо сейчас Короче, только это реально спасло — наркологическая помощь на дому круглосуточно качественно Через пару часов человек пришёл в себя В общем, не потеряйте контакты — нарколог на дом 24 часа [url=https://kapelnicza.narkolog-na-dom-sankt-peterburg14.ru]нарколог на дом 24 часа[/url] Нарколог на дом — это реальный выход Перешлите тем кто в такой же ситуации

  • Люди помогите советом Близкий человек уже несколько дней в запое Жена в истерике В больницу тащить страшно Короче, только капельница реально спасла — капельница от похмелья стоимость доступная Приехали через 40 минут В общем, вся инфа по ссылке — вызов нарколога капельница [url=https://zapoj.kapelnica-ot-zapoya-nizhnij-novgorod-uvw.ru]вызов нарколога капельница[/url] Капельница от запоя — это реальный выход Перешлите тем кто в такой же ситуации

  • Spot on with this write-up, I actually assume this website needs far more consideration. I will in all probability be once more to learn rather more, thanks for that info.

  • Hey there are using WordPress for your site platform? I’m new to the blog world but I’m
    trying to get started and create my own. Do you
    require any html coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  • Wonderful beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog website?

    The account aided me a acceptable deal. I had been tiny bit acquainted
    of this your broadcast offered bright clear idea

  • Hi there colleagues, its great piece of writing on the topic of
    cultureand completely explained, keep it up all the time.

  • This is a great tip particularly to those fresh to the blogosphere.

    Simple but very accurate info… Thanks for sharing this one.
    A must read post!

  • I know this if off topic but I’m looking into starting my own blog
    and was curious what all is required to get
    setup? I’m assuming having a blog like yours would cost a
    pretty penny? I’m not very internet smart so I’m
    not 100% certain. Any recommendations or advice would be greatly appreciated.
    Appreciate it

  • Its like you learn my thoughts! You seem to grasp a lot about this,
    such as you wrote the e-book in it or something.
    I believe that you can do with some p.c. to force the message house a little bit,
    but other than that, this is wonderful blog. An excellent read.
    I will certainly be back.

  • Hello, i think that i saw you visited my web site so i came to “return the favor”.I
    am trying to find things to improve my website!I suppose its ok to use
    a few of your ideas!!

  • Здорова, народ Муж просто потерял себя Дети напуганы В больницу тащить страшно Короче, врач приехал и поставил систему — помощь нарколога на дому Приехал через 40 минут В общем, телефон и цены тут — нарколога на дом казань [url=https://alkogolizm.narkologicheskaya-pomoshh-v-kazani16.ru]https://alkogolizm.narkologicheskaya-pomoshh-v-kazani16.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  • Казань, всем привет Муж просто потерял себя Жена в истерике В больницу тащить страшно Короче, только это реально спасло — наркологическая служба с опытом Приехал через 40 минут В общем, не потеряйте контакты — вызов врача нарколога цена [url=https://lechenie.narkologicheskaya-pomoshh-v-kazani016.ru]https://lechenie.narkologicheskaya-pomoshh-v-kazani016.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  • I delight in, cause I discovered just what I used to be looking for.
    You have ended my 4 day lengthy hunt! God Bless you man. Have a great day.

    Bye

  • Great beat ! I wish to apprentice while you amend your website, how could
    i subscribe for a blog web site? The account aided
    me a acceptable deal. I had been a little bit acquainted of
    this your broadcast provided bright clear concept

  • Excellent post. I used to be checking continuously this weblog and
    I am inspired! Extremely useful information specially the ultimate section :
    ) I handle such information a lot. I used to be looking
    for this particular information for a long time.
    Thanks and good luck.

Comments are closed.