Nginx 配置 PHP 站点指南
简介
Nginx 是一款高性能的 HTTP 和反向代理服务器,常用于构建高性能的 Web 应用,在配置 PHP 站点时,Nginx 与 PHP-FPM(FastCGI Process Manager)结合使用,可以有效地提高站点的响应速度和并发处理能力,本文将详细介绍如何配置 Nginx 以支持 PHP 站点。
准备工作
在开始配置之前,请确保已安装以下软件:
以下是一个简单的安装步骤:
# 安装 Nginxsudo apt-get Install nginx# 安装 PHPsudo apt-get install php# 安装 PHP-FPMsudo apt-get install php-fpm# 安装 FastCGIsudo apt-get install libfcgi-dev
配置 Nginx
编辑 Nginx 配置文件
sudo nano /etc/nginx/sites-available/default
修改配置文件,添加以下内容:
server {listen 80;server_name yourdomain.com www.yourdomain.com;root /var/www/html;index index.php index.html index.htm;location / {try_files $uri $uri/ /index.php?$query_string;}location ~ .php$ {include snippets/fastcgi-php.conf;fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的 PHP 版本修改fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;include fastcgi_params;}}
重载 Nginx 配置
sudo Systemctl reload nginx
配置 PHP-FPM
编辑 PHP-FPM 配置文件
sudo nano /etc/php/7.4/fpm/pool.d/www.conf
修改以下配置:
; listen = /var/run/php/php7.4-fpm.socklisten = 127.0.0.1:9000
重启 PHP-FPM 服务
sudo systemctl restart php7.4-fpm
测试配置
创建一个简单的 PHP 文件
问题 1:如何修改 Nginx 监听的端口?
解答:在 Nginx 配置文件中,找到指令,将其值修改为你想要的端口号,将修改为
listen 8080;
。
问题 2:如何为多个域名配置相同的 PHP 站点?
解答:为每个域名创建一个 Nginx 配置文件,并在
server_name
指令中添加对应的域名,为
example.com
和
subdomain.example.com
创建两个配置文件,并在其中分别添加以下内容:
server {listen 80;server_name example.com subdomain.example.com;# ... 其他配置 ...}














发表评论