如何在 Ubuntu 16.04 上为 Nginx 使用 OpenResty Web 框架

介绍

OpenResty是一个网络服务器,通过将它与许多有用的 Nginx 模块和 Lua 库相结合来扩展 Nginx。OpenResty 在扩展 Web 应用程序和服务方面表现出色。例如,其中一个模块允许您编写 Lua 代码,该代码将直接在 Nginx 工作者中执行,从而允许高性能的应用程序。

在本指南中,您将从源头上设置 OpenResty;某些发行版的预建包可能已过时;您还将探索一些简单的示例应用程序,使用 OpenResty 的独特功能。

前提条件

要遵循这个指南,你将需要:

请注意, Nginx 不应该安装,它包含在 OpenResty 中,并且提前安装会产生冲突。

步骤 1 — 下载 OpenResty 的源代码和依赖

在本节中,我们将从源头上安装OpenResty。

首先,从 OpenResty 网站上的 下载页面找到最新的 OpenResty 源代码版本。

1wget https://openresty.org/download/openresty-1.11.2.2.tar.gz

下载 PGP 密钥文件,以便我们可以验证文件的内容。

1wget https://openresty.org/download/openresty-1.11.2.2.tar.gz.asc

接下来,我们需要添加作者在下载页面上列出的公共密钥. 在写作时,这是公共密钥 A0E98066. 但是,请检查是否已更改;它在同一下载页面上列出。

1gpg --keyserver pgpkeys.mit.edu --recv-key A0E98066

您应该看到以下输出(使用您的用户名而不是 sammy):

 1[secondary_label Output]
 2gpg: directory `/home/sammy/.gnupg' created
 3gpg: new configuration file `/home/sammy/.gnupg/gpg.conf' created
 4gpg: WARNING: options in `/home/sammy/.gnupg/gpg.conf' are not yet active during this run
 5gpg: keyring `/home/sammy/.gnupg/secring.gpg' created
 6gpg: keyring `/home/sammy/.gnupg/pubring.gpg' created
 7gpg: requesting key A0E98066 from hkp server pgpkeys.mit.edu
 8gpg: /home/sammy/.gnupg/trustdb.gpg: trustdb created
 9gpg: key A0E98066: public key "Yichun Zhang (agentzh) <[email protected]>" imported
10gpg: Total number processed: 1
11gpg:               imported: 1  (RSA: 1)

检查公共密钥上的名称(在这种情况下,它是Yichun Zhang)是否符合OpenResty网站上列出的名称。

现在,检查签名文件是否匹配下载的 .tar.gz 文件。

1gpg openresty-1.11.2.2.tar.gz.asc

您将看到以下输出:

1[secondary_label Output]
2gpg: assuming signed data in `openresty-1.11.2.2.tar.gz'
3gpg: Signature made Thu 17 Nov 2016 10:24:29 PM UTC using RSA key ID A0E98066
4gpg: Good signature from "Yichun Zhang (agentzh) <[email protected]>"
5gpg: WARNING: This key is not certified with a trusted signature!
6gpg:          There is no indication that the signature belongs to the owner.
7Primary key fingerprint: 2545 1EB0 8846 0026 195B D62C B550 E09E A0E9 8066

你看到的警告是因为你没有亲自验证这个密钥是否属于所有者(即,你没有用自己的私钥签署公共密钥)。

然而,在这种情况下, Good signature表示这个文件确实是OpenResty的作者打算分发的文件,所以我们可以继续安装。

接下来,提取下载的文件并进入新创建的目录。

1tar -xvf openresty-1.11.2.2.tar.gz
2cd openresty-1.11.2.2

我们需要安装必要的工具来编译 OpenResty. 有关从源编译程序的更多信息,请参阅 此关于使用 make 来安装源包的教程

1sudo apt-get install build-essential

我们还需要安装一些其他包:

  • readline:这将由OpenResty用于命令行界面。
  • ncurses:这是OpenResty为命令行界面使用的另一款软件。
  • PCRE:这款软件将为OpenResty提供常规表达功能。
  • OpenSSL:OpenSSL用于安全通信,如TLS(HTTPS)。

要安装这些包,执行以下命令:

1sudo apt-get install libreadline-dev libncurses5-dev libpcre3-dev libssl-dev perl

我们现在拥有构建和安装OpenResty所需的所有组件。

步骤 2 – 安装 OpenResty

我们还将通过提供-j2旗帜来平行构建过程的一部分,这将告诉两项工作可以同时运行。这项命令将主要测试所有依赖性是否在您的系统上可用,并收集信息,这些信息将在以后的构建步骤中使用。

1./configure -j2 --with-pcre-jit --with-ipv6

然后你可以构建OpenResty,再次通过提供-j2旗帜进行平行化,这将构建OpenResty本身。

1make -j2

最后,你可以安装OpenResty。使用sudo确保所有文件可以被复制到系统上的正确位置,这样OpenResty可以在运行时找到它们。

1sudo make install

您需要允许您的防火墙中的 HTTP 连接,以便 Web 服务器工作。

1sudo ufw allow http

如果你要使用它,你也可以选择允许HTTPS与sudo ufw允许HTTPS,你可以通过检查它的状态来验证防火墙的变化。

1sudo ufw status

您应该在显示的输出中看到允许的 HTTP 流量(端口 80),如果您添加了 HTTPS (端口 443)。

 1[secondary_label Output]
 2Status: active
 3
 4To Action From
 5--                         ------      ----
 6OpenSSH ALLOW Anywhere
 780 ALLOW Anywhere
 8443 ALLOW Anywhere
 9OpenSSH (v6)               ALLOW Anywhere (v6)
1080 (v6)                    ALLOW Anywhere (v6)
11443 (v6)                   ALLOW Anywhere (v6)

现在您可以检查安装是否成功. 首先,启动 OpenResty。

1sudo /usr/local/openresty/bin/openresty

如果命令成功,它将立即完成,而无需输出文本。在这种情况下,您可以在浏览器中访问http://your_server_ip。您将看到一个页面,上面写着欢迎来到OpenResty!**,并确认它已完全安装和工作。

您现在可以停止 OpenResty 服务器。

1sudo /usr/local/openresty/bin/openresty -s quit

OpenResty 已安装,但您仍然需要配置 OpenResty 以启动,以便不需要手动启动服务器。

步骤 3 – 设置 OpenResty 作为服务

在这里,我们将设置OpenResty作为一个服务,以便它在启动时自动启动。我们将使用systemd init服务来完成此操作.您可以阅读 This systemd basic tutorial 有关更多信息,以及 This unit file tutorial 有关单元文件的信息。

首先,创建一个新的systemd文件,使用nano或您最喜欢的文本编辑器。

1sudo nano /etc/systemd/system/openresty.service

对于本教程,我们将从新安装中复制默认的 Nginx systemd 文件,并对 OpenResty 进行修改. 完整的文件看起来像这样,应该粘贴到我们刚刚打开的文件中。

 1[label /etc/systemd/system/openresty.service]
 2# Stop dance for OpenResty
 3# A modification of the Nginx systemd script
 4# =======================
 5#
 6# ExecStop sends SIGSTOP (graceful stop) to the Nginx process.
 7# If, after 5s (--retry QUIT/5) OpenResty is still running, systemd takes control
 8# and sends SIGTERM (fast shutdown) to the main process.
 9# After another 5s (TimeoutStopSec=5), and if OpenResty is alive, systemd sends
10# SIGKILL to all the remaining processes in the process group (KillMode=mixed).
11#
12# Nginx signals reference doc:
13# http://nginx.org/en/docs/control.html
14#
15[Unit]
16Description=A dynamic web platform based on Nginx and LuaJIT.
17After=network.target
18
19[Service]
20Type=forking
21PIDFile=/run/openresty.pid
22ExecStartPre=/usr/local/openresty/bin/openresty -t -q -g 'daemon on; master_process on;'
23ExecStart=/usr/local/openresty/bin/openresty -g 'daemon on; master_process on;'
24ExecReload=/usr/local/openresty/bin/openresty -g 'daemon on; master_process on;' -s reload
25ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/openresty.pid
26TimeoutStopSec=5
27KillMode=mixed
28
29[Install]
30WantedBy=multi-user.target

单元部分:

*「After=network.target」使OpenResty在网络关闭后启动,以便OpenResty可以连接和聆听端口。

服务部分:

  • Type=forking'告诉systemd',我们在`ExecStart'中要求的进程将在背景中开始服务,在服务完成之后,这一进程将停止。
  • PIDFile=/run/openresty.pid' 告诉 systemd 在启动时在哪里找到 PID 文件 OpenResty 创建 。 这使得系统化`能够知道OpenResty是否还在运行。
  • ‘ExecStartPre=/usr/local/openresty/bin/openresty -t-q-g'daemon on; master_process on;'不启动就调用OpenResty脚本. " T " 旗告诉 OpenResty 我们只希望它测试配置文件; -q旗告诉它, 我们要压制任何非错误输出;-g 旗设定了全球指令 守护; 主进程 显示 OpenResty 我们希望它以守护进程的背景开始 。 我们将此脚本作为 ExecStartPre 执行, 这样 systemd` 就不会在配置文件无效时尝试启动 OpenResty , 因为它会在此命令上出错 。
  • `ExectStart=/usr/local/openresty/bin/openresty - g'daemon 打开;主进程打开;'实际开始 OpenReesty. (英语). 这与没有 " t " 旗的 " ExecStartPre " 相同。
  • ExecReload=/usr/local/openresty/bin/openresty - g'daemon 打开;主程序打开;' - 重新装入' 告诉系统化在我们运行系统化重装开关`时运行此命令。 '-s' 旗让 OpenResty 重新装入配置文件 。
  • ‘ExecStop=-/ sbin/ start- stop-守护程序' --quiet -- stop -- retry QUIT/5 -- pidfile / run/ openresty.pid 告诉 systemd 当 OpenResty 停止时运行此命令。 它向PID文件中所列的进程发送了SIGSTOP'。 如果5秒后仍然运行,系统化将通过以下两个选项来控制。 *Timeout StopSec=5' 告诉系统化',我们希望在5秒内停止这一进程。 如果不停止,`系统化'将强行尝试停止OpenRest。
  • KillMode=混合' 指定系统化`方式 尝试停止 5秒后仍未停止的 OpenResty 。 (英语)

安装部分中:

*「WantedBy=multi-user.target」表示「systemd」,如果服务已配置为在启动时启动,则我们希望该服务启动。

这就是 etc/systemd/system/openresty.service 文件的全部。接下来,我们需要定制 OpenResty Nginx 配置文件并启用该服务。

首先打开配置文件。

1sudo nano /usr/local/openresty/nginx/conf/nginx.conf

默认情况下,它将看起来像这样:

 1[label Default /usr/local/openresty/nginx/conf/nginx.conf]
 2#user nobody;
 3worker_processes 1;
 4
 5#error_log logs/error.log;
 6#error_log logs/error.log notice;
 7#error_log logs/error.log info;
 8
 9#pid logs/nginx.pid;
10
11events {
12    worker_connections 1024;
13}
14
15. . .

删除事件行前的一切,并用以下三行替换它:

 1[label Updated /usr/local/openresty/nginx/conf/nginx.conf]
 2user www-data;
 3worker_processes auto;
 4pid /run/openresty.pid;
 5
 6events {
 7    worker_connections 1024;
 8}
 9
10. . .

此文件将确保我们作为 www-data用户运行,并且systemd可以识别OpenResty运行时,因为OpenResty一旦启动将创建的pid行。

保存并关闭文件。

接下来,创建日志目录。

1sudo mkdir /var/log/openresty

重新加载systemd服务,以便它可以找到我们的文件。

1sudo systemctl daemon-reload

现在,通过systemd启动OpenResty。

1sudo systemctl start openresty

您现在可以再次访问「http://your_server_ip」并看到与之前相同的网页。

最后一步是启用该服务,以确保OpenResty在启动时启动。

1sudo systemctl enable openresty

您可以在我们的 服务和单元教程中了解有关管理systemd服务和单元的更多信息。

现在我们已经配置了服务,我们可以进一步配置OpenResty,以便它例如登录到一个常见的位置。

步骤 4 – 配置 OpenResty

为了配置 OpenResty,我们使用了默认的 Nginx 配置作为参考,以便它大多与您可能熟悉的内容相匹配。

首先,重新打开 OpenResty 配置文件:

1sudo nano /usr/local/openresty/nginx/conf/nginx.conf

这一次,我们将修改http块,并将这个http块中的服务器块移动到一个新的文件中,以获得更好的结构。

 1[label Current /usr/local/openresty/nginx/conf/nginx.conf]
 2user www-data;
 3worker_processes auto;
 4pid /run/openresty.pid;
 5
 6events {
 7    worker_connections 1024;
 8}
 9
10http {
11    include mime.types;
12    default_type application/octet-stream;
13
14    . . .
15}

然后,将下列内容复制到http块中,使您的整个文件看起来像这个样子,我们将一次性地进行更改。

 1[label /usr/local/openresty/nginx/conf/nginx.conf]
 2user www-data;
 3worker_processes auto;
 4pid /run/openresty.pid;
 5
 6events {
 7    worker_connections 1024;
 8}
 9
10http {
11    include mime.types;
12    default_type application/octet-stream;
13
14    sendfile on;
15    tcp_nopush on;
16    tcp_nodelay on;
17
18    keepalive_timeout 65;
19
20    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
21    ssl_prefer_server_ciphers on;
22
23    access_log /var/log/openresty/access.log;
24    error_log /var/log/openresty/error.log;
25
26    gzip on;
27    gzip_disable "msie6";
28
29    include ../sites/*;
30}

保存并关闭文件。

我们对默认文件所做的更改是:

  • 联合国 解说tcp_ nopush on; , 它告诉 OpenResty 只发送完整数据包 。 此选项在使用 sendfile 选项时有用, 它将允许 OpenResty 优化向客户端发送静态文件 。
  • 添加tcp_nodelay on;'。 此选项将尝试尽快发送数据包, 这似乎与上述选项相悖, 但使用时间不同 。 tcp_nodelay'只在HTTP请求上使用`keepalive'选项时使用,这是网络浏览器与网络服务器的连接,可避免在每次请求时启动HTTP连接的间接费用。
  • 添加并修改"ssl_protocols"和"sl_prefer_server_ciphers"行. 这些选项配置 OpenResty 的 SSL 选项 。 我们已经取消了那些容易被已知的HTTPS攻击的旧协议,例如POODLE攻击.
  • 添加 access_log error_log 线条, 以配置网络服务器日志的位置 。 我们把日志储存在上一个步骤中创建的`/var/log/openresty'目录上。
  • 对‘gzip on'不作评论,并添加‘gzip_disable'"msie6". 这些选项将配置 GZIP, 它将压缩网页, 从而减少要传输的数据 。 我们还加入了最后一个选项,因为Internet Explorer 6(以及更老的)并不总是能正确处理GZIP的内容.
  • 添加包括./站点/*;',其中说明 在/usr/local/openresty/nginx/sites`目录中查找额外配置文件的 OpenResty, 稍后我们将创建该目录 。
  • 删除所有 服务器 块, 我们将在此步骤稍后移动到一个新的文件 。 (英语)

接下来,创建我们在包括行中指定的新网站目录。

1sudo mkdir /usr/local/openresty/nginx/sites

创建默认网站。

1sudo nano /usr/local/openresty/nginx/sites/default.conf

这是从nginx.conf开始的原始服务器块的迁移,但有详细的内线评论。

 1[label /usr/local/openresty/nginx/sites/default.conf]
 2server {
 3    # Listen on port 80.
 4    listen 80 default_server;
 5    listen [::]:80 default_server;
 6
 7    # The document root.
 8    root /usr/local/openresty/nginx/html/default;
 9
10    # Add index.php if you are using PHP.
11    index index.html index.htm;
12
13    # The server name, which isn't relevant in this case, because we only have one.
14    server_name _;
15
16    # When we try to access this site...
17    location / {
18        # ... first attempt to serve request as file, then as a directory,
19        # then fall back to displaying a 404.
20        try_files $uri $uri/ =404;
21    }
22
23    # Redirect server error pages to the static page /50x.html.
24    error_page 500 502 503 504  /50x.html;
25    location = /50x.html {
26        root /usr/local/openresty/nginx/html;
27    }
28}

保存并关闭文件。

现在,为这个网站创建一个新目录。

1sudo mkdir /usr/local/openresty/nginx/html/default

然后将原始index.html从原始位置移动到新目录。

1sudo mv /usr/local/openresty/nginx/html/index.html /usr/local/openresty/nginx/html/default

最后,重新启动 OpenResty 以使用此新网站。

1sudo systemctl restart openresty

您现在可以再次访问http://your_server_ip并看到与以前相同的网页。

现在OpenResty已经完全配置,我们可以尝试一些由OpenResty引入的功能,这些功能默认情况下在Nginx中不可用。

步骤 5 — 使用 OpenResty Lua 模块

在本节中,我们将看看由OpenResty添加的不同模块的组合,这些模块都存在以适应Lua脚本。在这一步中,我们将修改 /usr/local/openresty/nginx/sites/default.conf,所以先打开它。

1sudo nano /usr/local/openresty/nginx/sites/default.conf

首先,我们将看看content_by_lua_block配置选项,从下面的示例配置中复制位置块,然后将其添加到服务器块中,在两个现有的位置块下面。

 1[label /usr/local/openresty/nginx/sites/default.conf content_by_lua_block example]
 2server {
 3    . . .
 4
 5    location /example {
 6         default_type 'text/plain';
 7
 8         content_by_lua_block {
 9             ngx.say('Hello, Sammy!')
10         }
11    }
12}

保存并关闭文件,然后重新加载配置。

1sudo systemctl reload openresty

如果您现在访问http://your_server_ip/example,您将看到一个页面,上面写着Hello, Sammy!

content_by_lua_block配置指令将其中的所有内容执行为Lua代码,在这里,我们使用Lua函数ngx.say将消息 **Hello, Sammy!**打印到页面上。

对于另一个示例,用以下代替位置 / 示例块的内容:

 1[label /usr/local/openresty/nginx/sites/default.conf content_by_lua_file example]
 2server {
 3    . . .
 4
 5    location /example {
 6         default_type 'text/plain';
 7
 8         content_by_lua_file /usr/local/openresty/nginx/html/default/index.lua;
 9    }
10}

content_by_lua_file 将 Lua 内容从外部文件中加载,所以让我们创建我们上面指定的内容: /usr/local/openresty/nginx/html/default/index.lua

1sudo nano /usr/local/openresty/nginx/html/default/index.lua

将以下内容添加到文件中,然后保存并关闭它。

1[label /usr/local/openresty/nginx/html/default/index.lua]
2local name = ngx.var.arg_name or "Anonymous"
3ngx.say("Hello, ", name, "!")

这是一个简单的Lua,它在URL中读取一个查询参数,‘名称’,并定制问候消息。

重新加载配置。

1sudo systemctl reload openresty

现在,请访问您的浏览器中的http://your_server_ip/example?name=Sammy。 这将显示 Hello, Sammy!. 您可以更改名称查询参数,或者完全省略。

1Hello, Sammy!

您也可以更改名称查询参数以显示任何其他名称。

<$>[警告] 警告: 不要将您正在从网络上加载的Lua文件放置在可访问的位置. 如果您这样做,如果有人访问该文件,您的应用程序代码可能会被包含。

结论

在本文中,您将设置 OpenResty,这将使您能够在 Nginx 工作者中使用 Lua 脚本. 可以创建更复杂的 Lua 脚本. 您还可以,例如,使用 Lua 脚本限制访问或使用 Lua 重写某些请求。 您可以在 lua-nginx 模块的 GitHub 页面找到文档。 甚至在 OpenResty 上使用 Lua 的完整 Web 框架,如 Lapis

如果您想了解更多信息,您可以访问 OpenResty 网站. 因为 OpenResty 只是一个扩展的 Nginx 安装,您也可以在 Nginx 服务器块教程中学习如何设置服务器块,但请确保将本教程中使用的路径替换为本教程中使用的路径。

Published At
Categories with 技术
comments powered by Disqus