好的,我帮你整理一份 Windows 下 Nginx + PHP 环境配置全流程,附带 测试方法和常见坑,可以直接照着操作。
一、准备工作
- 下载 Nginx
- 官网:https://nginx.org/en/download.html
- 推荐 稳定版(Stable)
- 下载后解压到任意目录,例如:
C:\nginx
- 下载 PHP
- 官网:https://windows.php.net/download
- 选择 Thread Safe 版本(TS)
- 下载 ZIP,解压到目录,例如:
C:\php - PHP 版本建议 >= 7.4
- 配置环境变量(可选)
- 将 PHP 路径加入系统 PATH,方便命令行执行
php -v
- 将 PHP 路径加入系统 PATH,方便命令行执行
二、配置 PHP
- 打开 PHP 目录,复制
php.ini-development→php.ini - 修改常用配置:
; 开启扩展
extension_dir = "ext"
extension=curl
extension=gd
extension=mysqli
; 设置时区
date.timezone = "Asia/Shanghai"
; 开启短标签(可选)
short_open_tag = On
- 测试 PHP CLI
php -v
三、配置 Nginx + PHP
- 打开 Nginx 安装目录,编辑
conf/nginx.conf - 配置 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
- 命令行进入 Nginx 目录:
start nginx
- 停止 Nginx:
nginx -s stop
- 重载配置:
nginx -s reload
六、测试环境
- 在 Nginx 根目录
html下创建index.php:
<?php
phpinfo();
- 浏览器访问:
http://localhost/index.php
- 如果能看到 PHP 信息页面,说明配置成功。
七、常见问题与解决
| 问题 | 解决方法 |
|---|---|
| 浏览器下载 PHP 文件 | 1. 检查 fastcgi_pass 是否启动 2. 检查 SCRIPT_FILENAME |
| 502 Bad Gateway | PHP FastCGI 未启动 或 端口错 |
| PHP 扩展未生效 | php.ini extension_dir 配置错误 |
| Nginx 启动报错 | 检查 nginx.conf 语法 nginx -t |
| 中文乱码 | PHP.ini 设置 default_charset = "UTF-8",Nginx 添加 charset utf-8; |
八、优化建议(可选)
- 设置 Nginx 日志目录,便于排查错误
- 启用 PHP OpCache,提高性能
- Windows 上不适合高并发生产环境,仅用于开发测试
- 配合 phpMyAdmin / MySQL 可快速搭建完整 LEMP 环境
九、一句话总结
Windows 下 Nginx + PHP = Nginx 负责路由 + PHP-CGI 负责处理,通过 FastCGI 端口通信。测试用 phpinfo.php 即可验证。