安装与配置 Nginx 和 PHP 的完整指南
随着现代网站和应用程序的不断发展,对服务器端语言的支持需求也日益增加,Nginx 作为一款高性能、轻量级的Web服务器,常用于静态文件加速和反向代理;而PHP则是一种广泛使用的脚本语言,常用于动态网页开发,本文将详细介绍如何在Ubuntu系统上安装和配置Nginx以及PHP,并展示它们如何协同工作。
准备环境
确保你的系统已经更新到最新版本:
sudo apt update && sudo apt upgrade -y
安装 Nginx
-
添加 Nginx 源:
sudo add-apt-repository ppa:nginx/stable
-
安装 Nginx:
sudo apt install nginx -y
-
启动并启用 Nginx:
sudo systemctl start nginx sudo systemctl enable nginx
安装 PHP
-
添加 PHP 源:
sudo add-apt-repository ppa:ondrej/php
-
安装 PHP:
sudo apt install php libapache2-mod-php php-mysql php-gd php-xml php-curl php-intl -y
-
创建 phpinfo 页面: 编辑 Apache 配置文件
/etc/apache2/sites-available/000-default.conf
,找到DocumentRoot
指令并将其指向你的网站目录(/var/www/html/yourwebsite
),然后保存文件。<Directory /var/www/html/yourwebsite> AllowOverride All </Directory>
-
重启 Apache 服务:
sudo systemctl restart apache2
配置 Nginx 以支持 PHP
编辑 Nginx 配置文件 /etc/nginx/nginx.conf
或 /etc/nginx/sites-available/default
,添加以下内容以支持 PHP:
server { listen 80; server_name yourdomain.com; root /var/www/html/yourwebsite; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据实际情况修改 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
将 yourdomain.com
替换为你的域名或 IP 地址。
- 重启 Nginx 使更改生效:
sudo systemctl restart nginx
测试配置
访问 http://yourdomain.com
应该能看到 Nginx 的默认页面,或者通过浏览器加载你的网站文件,应该能够看到 PHP 信息页面。
步骤介绍了如何在 Ubuntu 系统上安装并配置 Nginx 和 PHP,通过这些设置,你可以在一台服务器上同时提供静态和动态内容,满足不同的网站需求,对于更复杂的应用场景,可以根据实际需要调整配置文件,优化性能和安全性。