参考资料

  1. Nginx的启动与停止命令
  2. 如何识别Nginx遇到攻击时如何快速响应?
  3. NginxWebDAV模块配置详细说明以及案例
  4. NginxMemcached缓存模块详细说明以及案例
  5. 如何配置Nginx用户认证?
  6. Nginxrewrite重定向配置详解
  7. Nginx GitLab(配置归档工具)配置详细说明以及案例
  8. 实现完整离线浏览,需配合Service Worker

NginxPHP服务器环境搭建详细说明以及案例

Nginx + PHP 服务器环境搭建

1. 安装 Nginx

sudo apt update
sudo apt install nginx

2. 安装 PHP 和 PHP-FPM

sudo apt install php-fpm php-mysql

3. 配置 Nginx 使用 PHP-FPM

编辑 Nginx 配置文件:

sudo nano /etc/nginx/sites-available/default

server 块中添加以下内容:

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;
}

4. 重启 Nginx

sudo systemctl restart nginx

5. 测试 PHP

创建一个 PHP 测试文件:

sudo nano /var/www/html/info.php

内容如下:

<?php
phpinfo();
?>

访问 http://your_server_ip/info.php,确认 PHP 信息页面显示正常。

案例:部署一个简单的 PHP 应用

1. 创建项目目录

sudo mkdir -p /var/www/myapp
sudo chown -R $USER:$USER /var/www/myapp

2. 创建 PHP 文件

nano /var/www/myapp/index.php

内容如下:

<?php
echo "Hello, World!";
?>

3. 配置 Nginx

编辑 Nginx 配置文件:

sudo nano /etc/nginx/sites-available/myapp

内容如下:

server {
    listen 80;
    server_name myapp.com;

    root /var/www/myapp;
    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;
    }
}

启用配置并重启 Nginx:

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo systemctl restart nginx

4. 访问应用

在浏览器中访问 http://myapp.com,确认显示 "Hello, World!"。

总结

通过以上步骤,你可以成功搭建 Nginx + PHP 服务器环境,并部署一个简单的 PHP 应用。