Nginx 是一个高性能的 HTTP 和反向代理服务器,而 PHP 是一种广泛使用的服务器端脚本语言。Nginx 可以与 PHP 配合使用,来提供动态网页服务。以下是 Nginx 与 PHP 配合使用的一般步骤:
- 重启 Nginx 以应用配置更改:
sudo systemctl restart nginx - 重启 PHP-FPM 服务:
sudo systemctl restart php7.4-fpm # 根据你的 PHP 版本调整 - 创建一个名为
info.php的文件,包含以下内容:<?php phpinfo(); ?> - 将这个文件放置在 Nginx 的根目录下(例如
/var/www/html/)。 - 访问
http://example.com/info.php,你应该能看到 PHP 的信息页面。 - 确保你的 PHP 配置文件(例如
php.ini)中的设置是安全的。 - 考虑使用
.htaccess文件来进一步访问。 - 根据需要调整 Nginx 和 PHP-FPM 的配置,以优化性能和资源使用。
- 确保 Nginx 和 PHP-FPM 的日志记录是开启的,以便在出现问题时可以进行调试。
安装 PHP: 首先确保你的服务器上已经安装了 PHP。如果没有安装,可以通过包管理器安装,例如在 Ubuntu 上可以使用以下命令:
sudo apt-get update
sudo apt-get install php-fpm
配置 Nginx:
打开 Nginx 的配置文件,通常是 /etc/nginx/nginx.conf 或者 /etc/nginx/sites-available/default。
在 server 块中,配置 location 指令来处理 PHP 文件。例如:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的 PHP 版本调整
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
确保 fastcgi_pass 指向了正确的 PHP-FPM socket 文件。
重启 Nginx 和 PHP-FPM:
测试 PHP:
安全配置:
优化性能:
日志记录:
请根据你的具体环境和需求调整上述步骤。如果你使用的是不同的操作系统或者有特殊的配置需求,可能需要进行相应的调整。