好的,我帮你整理一份 Windows 下 Nginx + PHP 环境配置全流程,附带 测试方法和常见坑,可以直接照着操作。


一、准备工作

  1. 下载 Nginx
  2. 下载 PHP
  3. 配置环境变量(可选)
    • 将 PHP 路径加入系统 PATH,方便命令行执行 php -v

二、配置 PHP

  1. 打开 PHP 目录,复制 php.ini-developmentphp.ini
  2. 修改常用配置:
; 开启扩展
extension_dir = "ext"
extension=curl
extension=gd
extension=mysqli

; 设置时区
date.timezone = "Asia/Shanghai"

; 开启短标签(可选)
short_open_tag = On

  1. 测试 PHP CLI
php -v


三、配置 Nginx + PHP

  1. 打开 Nginx 安装目录,编辑 conf/nginx.conf
  2. 配置 PHP 处理(示例):
server {
    listen       80;
    server_name  localhost;

    root   html;   # 网站根目录,默认 Nginx\html
    index  index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP 脚本处理
    location ~ \.php$ {
        include        fastcgi_params;
        fastcgi_pass   127.0.0.1:9000;  # PHP-FPM 监听端口
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    }

    location ~ /\.ht {
        deny all;
    }
}


四、启动 PHP 的 FastCGI

在 PHP 目录打开命令行:

php-cgi -b 127.0.0.1:9000

说明:

  • -b 127.0.0.1:9000 表示监听本地 9000 端口
  • FastCGI 一旦关闭,Nginx 无法解析 PHP

💡 建议做成 Windows 服务或使用 php-cgi.exe + NSSM 工具运行常驻


五、启动 Nginx

  1. 命令行进入 Nginx 目录:
start nginx

  1. 停止 Nginx:
nginx -s stop

  1. 重载配置:
nginx -s reload


六、测试环境

  1. 在 Nginx 根目录 html 下创建 index.php
<?php
phpinfo();

  1. 浏览器访问:
http://localhost/index.php

  1. 如果能看到 PHP 信息页面,说明配置成功。

七、常见问题与解决

问题解决方法
浏览器下载 PHP 文件1. 检查 fastcgi_pass 是否启动 2. 检查 SCRIPT_FILENAME
502 Bad GatewayPHP FastCGI 未启动 或 端口错
PHP 扩展未生效php.ini extension_dir 配置错误
Nginx 启动报错检查 nginx.conf 语法 nginx -t
中文乱码PHP.ini 设置 default_charset = "UTF-8",Nginx 添加 charset utf-8;

八、优化建议(可选)

  1. 设置 Nginx 日志目录,便于排查错误
  2. 启用 PHP OpCache,提高性能
  3. Windows 上不适合高并发生产环境,仅用于开发测试
  4. 配合 phpMyAdmin / MySQL 可快速搭建完整 LEMP 环境

九、一句话总结

Windows 下 Nginx + PHP = Nginx 负责路由 + PHP-CGI 负责处理,通过 FastCGI 端口通信。测试用 phpinfo.php 即可验证。