Nginx 是一个高性能的 HTTP 和反向代理服务器,以及一个 IMAP/POP3/SMTP 代理服务器。它被广泛应用于各种场景,包括网站服务器、API 服务器、负载均衡等。而 PHP 作为一种流行的服务器端脚本语言,与 Nginx 的结合可以实现高效的网站应用部署。本文将详细介绍如何通过编译 Nginx 来实现 PHP 的完美兼容。
1. 准备工作
在开始编译 Nginx 之前,确保你的系统中已安装以下软件:
- GCC:用于编译 Nginx 和 PHP。
- CMake:用于构建 Nginx。
- Autoconf:用于自动配置 Nginx。
- Automake:用于自动生成 Makefile。
- Libpcre:用于正则表达式处理。
- zlib:用于数据压缩。
- openssl:用于 HTTPS 支持。
你可以使用以下命令安装这些软件:
sudo apt-get update
sudo apt-get install build-essential cmake autoconf automake libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
2. 下载 Nginx 源码
从 下载最新的 Nginx 源码包。
wget http://nginx.org/download/nginx-1.21.6.tar.gz
tar -zxf nginx-1.21.6.tar.gz
cd nginx-1.21.6
3. 配置 Nginx
在编译 Nginx 之前,需要配置 Nginx。你可以使用以下命令进行配置:
./configure --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_gzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_stub_status_module --with-http_browser_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_perl_module --with-pcre_jit --with-cc-opt='-O2' --with-ld-opt='-Wl,-rpath,/usr/local/nginx/lib'
这里我们添加了一些模块来增强 Nginx 的功能,例如 HTTPS 支持、虚拟主机、邮件服务器等。同时,我们还使用了 -Wl,-rpath,/usr/local/nginx/lib
参数来指定库文件的搜索路径。
4. 编译和安装 Nginx
完成配置后,可以使用以下命令编译和安装 Nginx:
make
sudo make install
这将编译 Nginx 并将其安装到 /usr/local/nginx
目录下。
5. 配置 PHP-FPM
接下来,需要配置 PHP-FPM(FastCGI Process Manager)来处理 PHP 脚本。首先,从 下载最新的 PHP 源码包。
wget https://cdn.jsdelivr.net/php@8.0.15/php-8.0.15.tar.gz
tar -zxf php-8.0.15.tar.gz
cd php-8.0.15
然后,使用以下命令配置 PHP:
./configure --enable-fpm --with-openssl --with-zlib --with-pdo --with-pdo-mysql --with-mysql --enable-mbstring --enable-xml --enable-bcmath --enable-json --enable-zip --with-curl --enable-ftp --with-gettext --enable-opcache --enable-fileinfo --with-pear
这里我们添加了一些扩展来增强 PHP 的功能,例如 PDO、MySQL、MBString、XML、Bcmath、JSON、Zip、Curl、FTP、gettext、opcache 和 fileinfo。
编译和安装 PHP:
make
sudo make install
这将在 /usr/local/php
目录下安装 PHP。
6. 配置 Nginx 与 PHP
http {
...
server {
listen 80;
server_name localhost;
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
...
}
...
}
这里我们配置了 Nginx 来监听 80 端口,并将