插件窝 干货文章 macbook nginx php环境如何搭建

macbook nginx php环境如何搭建

Nginx PHP bash 安装 1000    来源:    2025-04-22

MacBook 上搭建 Nginx + PHP 环境的完整指南

准备工作

  1. 确保你的 MacBook 已经安装了 Homebrew(如果没有安装,请先安装) bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

安装 Nginx

  1. 使用 Homebrew 安装 Nginx:

    brew install nginx
    
  2. 启动 Nginx 服务:

    brew services start nginx
    
  3. 验证 Nginx 是否运行:

    • 打开浏览器访问 http://localhost:8080
    • 应该能看到 Nginx 欢迎页面

安装 PHP

  1. 使用 Homebrew 安装 PHP(以 PHP 8.2 为例):

    brew install php
    
  2. 启动 PHP-FPM 服务:

    brew services start php
    
  3. 验证 PHP 安装:

    php -v
    

配置 Nginx 支持 PHP

  1. 编辑 Nginx 配置文件:

    sudo nano /usr/local/etc/nginx/nginx.conf
    
  2. http 块中添加或修改 server 配置:

    server {
       listen       80;
       server_name  localhost;
       root         /usr/local/var/www;
       index        index.php index.html index.htm;
    
       location / {
           try_files $uri $uri/ =404;
       }
    
       location ~ \.php$ {
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
           include        fastcgi_params;
       }
    }
    
  3. 创建网站根目录:

    mkdir -p /usr/local/var/www
    
  4. 测试 Nginx 配置:

    sudo nginx -t
    
  5. 重启 Nginx:

    sudo nginx -s reload
    

测试 PHP 环境

  1. 创建一个测试 PHP 文件:

    echo "<?php phpinfo(); ?>" > /usr/local/var/www/info.php
    
  2. 在浏览器中访问:

    http://localhost/info.php
    

    应该能看到 PHP 信息页面

可选配置

修改 PHP 配置

  1. 编辑 PHP 配置文件:

    nano /usr/local/etc/php/8.2/php.ini
    
  2. 根据需要修改配置,例如:

    upload_max_filesize = 20M
    post_max_size = 20M
    memory_limit = 256M
    

设置开机启动

brew services start nginx
brew services start php

常见问题解决

  1. 端口冲突:如果 80 端口被占用,可以修改 Nginx 监听端口
  2. 权限问题:确保 /usr/local/var/www 目录有正确的读写权限
  3. PHP 不执行:检查 Nginx 配置中的 fastcgi_pass 是否正确指向 PHP-FPM

开发工具推荐

  1. 数据库:可以安装 MySQL 或 MariaDB

    brew install mysql
    
  2. PHP 扩展:使用 pecl 安装需要的扩展

    pecl install xdebug
    
  3. Composer:PHP 依赖管理工具

    brew install composer
    

这样你就成功在 MacBook 上搭建了 Nginx + PHP 的开发环境!