如何在 Ubuntu 上安装和优化 Apache
Apache
![](/data/attachment/album/201805/25/103013e2pkoalbrkk2t2rz.jpg)


这是我们的 LAMP 系列教程的开始：如何在 Ubuntu 上安装 Apache web 服务器。


这些说明适用于任何基于 Ubuntu 的发行版，包括 Ubuntu 14.04、 Ubuntu 16.04、 [Ubuntu 18.04](https://thishosting.rocks/ubuntu-18-04-new-features-release-date/)，甚至非 LTS 的 Ubuntu 发行版，例如 Ubuntu 17.10。这些说明经过测试并为 Ubuntu 16.04 编写。


Apache (又名 httpd) 是最受欢迎和使用最广泛的 web 服务器，所以这应该对每个人都有用。


### 开始安装 Apache 之前


在我们开始之前，这里有一些要求和说明：


* Apache 可能已经在你的服务器上安装了，所以开始之前首先检查一下。你可以使用 `apachectl -V` 命令来显示你正在使用的 Apache 的版本和一些其他信息。
* 你需要一个 Ubuntu 服务器。你可以从 [Vultr](https://thishosting.rocks/go/vultr/) 购买一个，它们是[最便宜的云托管服务商](https://thishosting.rocks/cheap-cloud-hosting-providers-comparison/)之一。它们的服务器价格每月 2.5 美元起。（LCTT 译注：广告 ≤\_≤ ）
* 你需要有 root 用户或具有 sudo 访问权限的用户。下面的所有命令都由 root 用户执行，所以我们不必为每个命令都添加 `sudo`。
* 如果你使用 Ubuntu，则需要[启用 SSH](https://thishosting.rocks/how-to-enable-ssh-on-ubuntu/)，如果你使用 Windows，则应该使用类似 [MobaXterm](https://mobaxterm.mobatek.net/) 的 SSH 客户端。


这就是全部要求和注释了，让我们进入安装过程。


### 在 Ubuntu 上安装 Apache


你需要做的第一件事就是更新 Ubuntu，这是在你做任何事情之前都应该做的。你可以运行：



```
apt-get update && apt-get upgrade

```

接下来，安装 Apache，运行以下命令：



```
apt-get install apache2

```

如果你愿意，你也可以安装 Apache 文档和一些 Apache 实用程序。对于我们稍后将要安装的一些模块，你将需要一些 Apache 实用程序。



```
apt-get install apache2-doc apache2-utils

```

\**就是这样。你已经成功安装了 Apache \**


你仍然需要配置它。


### 在 Ubuntu 上配置和优化 Apache


你可以在 Apache 上做各种各样的配置，但是主要的和最常见的配置将在下面做出解释。


#### 检查 Apache 是否正在运行


默认情况下，Apache 设置为在机器启动时自动启动，因此你不必手动启用它。你可以使用以下命令检查它是否正在运行以及其他相关信息：



```
systemctl status apache2

```

[![check if apache is running](/data/attachment/album/201805/25/103025dogk7qugjoqgeggd.jpg)](https://thishosting.rocks/wp-content/uploads/2018/01/apache-running.jpg)


并且你可以检查你正在使用的版本：



```
apachectl -V

```

一种更简单的检查方法时访问服务器的 IP 地址，如果你得到默认的 Apache 页面，那么一切都正常。


#### 更新你的防火墙


如果你使用防火墙（你应该使用它），则可能需要更新防火墙规则并允许访问默认端口。Ubuntu 上最常用的防火墙是 UFW，因此以下说明使用于 UFW。


要允许通过 80（http）和 443（https）端口的流量，运行以下命令：



```
ufw allow 'Apache Full'

```

#### 安装常见的 Apache 模块


一些模块经常被建议使用，所以你应该安装它们。我们将包含最常见模块的说明：


##### 使用 PageSpeed 加速你的网站


PageSpeed 模块将自动优化并加速你的 Apache 服务器。


首先，进入 [PageSpeed 下载页](https://www.modpagespeed.com/doc/download)并选择你需要的的文件。我们使用的是 64 位 Ubuntu 服务器，所以我们安装最新的稳定版本。使用 `wget` 下载它：



```
wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-stable_current_amd64.deb

```

然后，使用以下命令安装它：



```
dpkg -i mod-pagespeed-stable_current_amd64.deb
apt-get -f install

```

重启 Apache 以使更改生效：



```
systemctl restart apache2

```

##### 使用 mod\_rewrite 模块启动重写/重定向


顾名思义，该模块用于重写（重定向）。如果你使用 WordPress 或任何其他 CMS 来处理此问题，你就需要它。要安装它，只需运行：



```
a2enmod rewrite

```

然后再次重新启动 Apache。你可能需要一些额外的配置，具体取决于你使用的 CMS，如果有的话。为你的设置 Google 一下得到它的具体说明。


##### 使用 ModSecurity 模块保护你的 Apache


顾名思义，ModSecurity 是一个用于安全性的模块，它基本上起着防火墙的作用，它可以监控你的流量。要安装它，运行以下命令：



```
apt-get install libapache2-modsecurity

```

再次重启 Apache：



```
systemctl restart apache2

```

ModSecurity 自带了一个默认的设置，但如果你想扩展它，你可以使用 [OWASP 规则集](https://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project)。


##### 使用 mod\_evasive 模块抵御 DDoS 攻击


尽管 mod\_evasive 在防止攻击方面有多大用处值得商榷，但是你可以使用它来阻止和防止服务器上的 DDoS 攻击。要安装它，使用以下命令：



```
apt-get install libapache2-mod-evasive

```

默认情况下，mod\_evasive 是禁用的，要启用它，编辑以下文件：



```
nano /etc/apache2/mods-enabled/evasive.conf

```

取消注释所有行（即删除 `#`），根据你的要求进行配置。如果你不知道要编辑什么，你可以保持原样。


[![mod_evasive](/data/attachment/album/201805/25/103026p252ibido5vcjiow.jpg)](https://thishosting.rocks/wp-content/uploads/2018/01/mod_evasive.jpg)


创建一个日志文件：



```
mkdir /var/log/mod_evasive
chown -R www-data:www-data /var/log/mod_evasive

```

就是这样。现在重启 Apache 以使更改生效。



```
systemctl restart apache2

```

你可以安装和配置[附加模块](https://httpd.apache.org/docs/2.4/mod/)，但完全取决于你和你使用的软件。它们通常不是必需的。甚至我们上面包含的 4 个模块也不是必需的。如果特定应用需要模块，那么它们可能会注意到这一点。


#### 用 Apache2Buddy 脚本优化 Apache


Apache2Buddy 是一个可以自动调整 Apache 配置的脚本。你唯一需要做的就是运行下面的命令，脚本会自动完成剩下的工作：



```
curl -sL https://raw.githubusercontent.com/richardforth/apache2buddy/master/apache2buddy.pl | perl

```

如果你没有安装 `curl`，那么你可能需要安装它。使用以下命令来安装 `curl`：



```
apt-get install curl

```

#### 额外配置


用 Apache 还可以做一些额外的东西，但我们会留下它们作为另一个教程。像启用 http/2 支持，关闭（或打开） KeepAlive，调整你的 Apache 甚至更多。这些东西你现在不需要做，但是如果你在网上找到了教程，并且如果你等不及我们的教程，那就去做吧。


### 使用 Apache 创建你的第一个网站


现在我们已经完成了所有的调优工作，让我们开始创建一个实际的网站。按照我们的指示创建一个简单的 HTML 页面和一个在 Apache 上运行的虚拟主机。


你需要做的第一件事是为你的网站创建一个新的目录。运行以下命令来执行此操作：



```
mkdir -p /var/www/example.com/public_html

```

当然，将 `example.com` 替换为你所需的域名。你可以从 [Namecheap](https://thishosting.rocks/neamcheap-review-cheap-domains-cool-names) 获得一个便宜的域名。


不要忘记在下面的所有命令中替换 `example.com`。


接下来，创建一个简单的静态网页。创建 HTML 文件：



```
nano /var/www/example.com/public_html/index.html

```

粘贴这些：



```
<html>
     <head>
       <title>Simple Page</title>
     </head>
     <body>
       <p>If you're seeing this in your browser then everything works.</p>
     </body>
</html>

```

保存并关闭文件。


配置目录的权限：



```
chown -R www-data:www-data /var/www/example.com
chmod -R og-r /var/www/example.com

```

为你的网站创建一个新的虚拟主机：



```
nano /etc/apache2/sites-available/example.com.conf

```

粘贴以下内容：



```
<VirtualHost *:80>
     ServerAdmin admin@example.com
     ServerName example.com
     ServerAlias www.example.com
   
     DocumentRoot /var/www/example.com/public_html
    
     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

```

这是一个基础的虚拟主机。根据你的设置，你可能需要更高级的 `.conf` 文件。


在更新所有内容后保存并关闭文件。


现在，使用以下命令启用虚拟主机：



```
a2ensite example.com.conf

```

最后，重启 Apache 以使更改生效：



```
systemctl restart apache2

```

这就是全部了，你做完了。现在你可以访问 example.com 并查看你的页面。




---


via: <https://thishosting.rocks/how-to-install-optimize-apache-ubuntu/>


作者：[ThisHosting](https://thishosting.rocks) 译者：[MjSeven](https://github.com/MjSeven) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
This is the beginning of our LAMP tutorial series: how to install the Apache web server on Ubuntu.


These instructions should work on any Ubuntu-based distro, including Ubuntu 16.04, [Ubuntu 18.04](https://thishosting.rocks/ubuntu-18-04-new-features-release-date/), Ubuntu 20.04 and even non-LTS Ubuntu releases like Ubuntu 20.10. They were tested and written for Ubuntu 18.04.

Apache (aka httpd) is the most popular and most widely used web server, so this should be useful for everyone.

## Before we begin installing Apache

Some requirements and notes before we begin:

- Apache may already be installed on your server, so check if it is first. You can do so with the “apachectl -V” command that outputs the Apache version you’re using and some other information.
- You’ll need an Ubuntu server. You can buy one from
[Vultr](https://thishosting.rocks/go/vultr/), they’re one of the[best and cheapest cloud hosting providers](https://thishosting.rocks/cheap-cloud-hosting-providers-comparison/). Their servers start from $2.5 per month. - You’ll need the root user or a user with sudo access. All commands below are executed by the root user so we didn’t have to append ‘sudo’ to each command.
- You’ll need
[SSH enabled](https://thishosting.rocks/how-to-enable-ssh-on-ubuntu/)if you use Ubuntu or an SSH client like[MobaXterm](https://mobaxterm.mobatek.net/)if you use Windows.

That’s most of it. Let’s move onto the installation.





## Install Apache on Ubuntu

The first thing you always need to do is update Ubuntu before you do anything else. You can do so by running:

apt-get update && apt-get upgrade

Next, to install Apache, run the following command:

apt-get install apache2

If you want to, you can also install the Apache documentation and some Apache utilities. You’ll need the Apache utilities for some of the modules we’ll install later.

apt-get install apache2-doc apache2-utils

**And that’s it. You’ve successfully installed Apache.**

You’ll still need to configure it.

## Configure and Optimize Apache on Ubuntu

There are various configs you can do on Apache, but the main and most common ones are explained below.

### Check if Apache is running

By default, Apache is configured to start automatically on boot, so you don’t have to enable it. You can check if it’s running and other relevant information with the following command:

systemctl status apache2

And you can check what version you’re using with

apachectl -V

A simpler way of checking this is by visiting your server’s IP address. If you get the default Apache page, then everything’s working fine.

### Update your firewall

If you use a firewall (which you should), you’ll probably need to update your firewall rules and allow access to the default ports. The most common firewall used on Ubuntu is UFW, so the instructions below are for UFW.

To allow traffic through both the 80 (http) and 443 (https) ports, run the following command:

ufw allow 'Apache Full'

### Install common Apache modules

Some modules are frequently recommended and you should install them. We’ll include instructions for the most common ones:

#### Speed up your website with the PageSpeed module

The PageSpeed module will optimize and speed up your Apache server automatically.

First, go to the [PageSpeed download page](https://www.modpagespeed.com/doc/download) and choose the file you need. We’re using a 64-bit Ubuntu server and we’ll install the latest stable version. Download it using wget:

wget https://dl-ssl.google.com/dl/linux/direct/mod-pagespeed-stable_current_amd64.deb

Then, install it with the following commands:

dpkg -i mod-pagespeed-stable_current_amd64.deb apt-get -f install

Restart Apache for the changes to take effect:

systemctl restart apache2

#### Enable rewrites/redirects using the mod_rewrite module

This module is used for rewrites (redirects), as the name suggests. You’ll need it if you use WordPress or any other CMS for that matter. To install it, just run:

a2enmod rewrite

And restart Apache again. You may need some extra configurations depending on what CMS you’re using, if any. Google it for specific instructions for your setup.

#### Secure your Apache with the ModSecurity module

ModSecurity is a module used for security, again, as the name suggests. It basically acts as a firewall, and it monitors your traffic. To install it, run the following command:

apt-get install libapache2-modsecurity

And restart Apache again:

systemctl restart apache2

ModSecurity comes with a default setup that’s enough by itself, but if you want to extend it, you can use the [OWASP rule set](https://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project).

#### Block DDoS attacks using the mod_evasive module

You can use the mod_evasive module to block and prevent DDoS attacks on your server, though it’s debatable how useful it is in preventing attacks. To install it, use the following command:

apt-get install libapache2-mod-evasive

By default, mod_evasive is disabled, to enable it, edit the following file:

nano /etc/apache2/mods-enabled/evasive.conf

And uncomment all the lines (remove #) and configure it per your requirements. You can leave everything as-is if you don’t know what to edit.

And create a log file:

mkdir /var/log/mod_evasive chown -R www-data:www-data /var/log/mod_evasive

That’s it. Now restart Apache for the changes to take effect:

systemctl restart apache2

There are [additional modules](https://httpd.apache.org/docs/2.4/mod/) you can install and configure, but it’s all up to you and the software you’re using. They’re usually not required. Even the 4 modules we included are not required. If a module is required for a specific application, then they’ll probably note that.

### Optimize Apache with the Apache2Buddy script

Apache2Buddy is a script that will automatically fine-tune your Apache configuration. The only thing you need to do is run the following command and the script does the rest automatically:

curl -sL https://raw.githubusercontent.com/richardforth/apache2buddy/master/apache2buddy.pl | perl

You may need to install curl if you don’t have it already installed. Use the following command to install curl:

apt-get install curl

### Additional configurations

There’s some extra stuff you can do with Apache, but we’ll leave them for another tutorial. Stuff like enabling http/2 support, turning off (or on) KeepAlive, tuning your Apache even more. You don’t have to do any of this, but you can find tutorials online and do it if you can’t wait for our tutorials.

## Create your first website with Apache

Now that we’re done with all the tuning, let’s move onto creating an actual website. Follow our instructions to create a simple HTML page and a virtual host that’s going to run on Apache.

The first thing you need to do is create a new directory for your website. Run the following command to do so:

mkdir -p /var/www/example.com/public_html

Of course, replace example.com with your desired domain. You can get a cheap domain name from [Namecheap](https://thishosting.rocks/neamcheap-review-cheap-domains-cool-names).

*Don’t forget to replace example.com in all of the commands below.*

Next, create a simple, static web page. Create the HTML file:

nano /var/www/example.com/public_html/index.html

And paste this:

<html> <head> <title>Simple Page</title> </head> <body> <p>If you're seeing this in your browser then everything works.</p> </body> </html>

Save and close the file.

Configure the permissions of the directory:

chown -R www-data:www-data /var/www/example.com chmod -R og-r /var/www/example.com

Create a new virtual host for your site:

nano /etc/apache2/sites-available/example.com.conf

And paste the following:

<VirtualHost *:80> ServerAdmin admin@example.com ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>

This is a basic virtual host. You may need a more advanced .conf file depending on your setup.

Save and close the file after updating everything accordingly.

Now, enable the virtual host with the following command:

a2ensite example.com.conf

And finally, restart Apache for the changes to take effect:

systemctl restart apache2

That’s it. You’re done. Now you can visit example.com and view your page.