首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Mac OS 搭建 Nginx + PHP + MySQL 開發環境教程

     編輯:PHP 相關知識

Mac OS 搭建 Nginx + PHP + MySQL 開發環境教程

Mac 開發環境首選 Homebrew 套件管理器,自動解決依賴,極大簡化安裝流程。

一、安裝 Homebrew

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

常用指令:

brew update          # 更新套件索引
brew search pkg_name # 搜尋套件
brew install pkg_name # 安裝套件

二、安裝與配置 Nginx

brew install nginx

配置目錄:/usr/local/etc/nginx/。建立 conf.d/ 存放虛擬主機配置。

nginx.conf 主配置

worker_processes 1;
error_log /usr/local/var/log/nginx/error.log warn;
pid /usr/local/var/run/nginx.pid;

events {
    worker_connections 256;
}

http {
    include mime.types;
    default_type application/octet-stream;
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /usr/local/var/log/nginx/access.log main;
    port_in_redirect off;
    sendfile on;
    keepalive_timeout 65;
    include /usr/local/etc/nginx/conf.d/*.conf;
}

conf.d/default.conf 虛擬主機

server {
    listen 8080;
    server_name localhost;
    root /Users/your_name/nginx_sites/;  # 修改為你的專案目錄

    location / {
        index index.php;
        autoindex on;
    }

    location ~ \.php$ {
        include /usr/local/etc/nginx/fastcgi.conf;
        fastcgi_intercept_errors on;
        fastcgi_pass 127.0.0.1:9000;
    }
}

三、配置 PHP-FPM

macOS 10.9+ 內建 PHP 與 PHP-FPM,無需額外安裝。

sudo cp /private/etc/php-fpm.conf.default /private/etc/php-fpm.conf
vim /private/etc/php-fpm.conf

修改 error_log 路徑(預設被註釋):

error_log = /usr/local/var/log/php-fpm.log

否則啟動會報日誌路徑不存在錯誤。

四、安裝與配置 MySQL

brew install mysql

常用指令:

mysql.server start  # 啟動
mysql.server stop   # 停止

執行安全初始化腳本:

mysql_secure_installation

依提示設定 root 密碼、移除匿名帳號、禁止 root 遠端登入、移除 test 資料庫。

五、驗證環境

  1. 在 Nginx root 目錄建立 index.php:<?php phpinfo(); ?>
  2. 啟動服務:
sudo nginx           # 啟動 Nginx
sudo nginx -s reload # 重載配置
sudo php-fpm         # 啟動 PHP-FPM
  1. 瀏覽器訪問 https://localhost:8080,應顯示 PHP 資訊頁。

常見問題

  • 權限錯誤:確保 Nginx/PHP-FPM 執行使用者對專案目錄有讀取權限。
  • fastcgi.conf 路徑:Homebrew 安裝的 Nginx 預設包含此檔,路徑為 /usr/local/etc/nginx/fastcgi.conf。
  • 埠口衝突:8080 被佔用時修改 listen 指令。

至此,Mac 上完整的 LEMP 開發環境已就緒,可直接進行現代 PHP 專案開發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved