插件窝 干货文章 nginx中怎么配置pathinfo模式

nginx中怎么配置pathinfo模式

配置 fastcgi index PHP 237    来源:    2025-04-26

Nginx 配置 Pathinfo 模式

Pathinfo 模式是一种 URL 重写方式,常用于 PHP 框架(如 ThinkPHP、Laravel 等),它允许通过 /index.php/controller/action 这样的 URL 形式访问应用。

基础配置

在 Nginx 中配置 Pathinfo 模式需要修改 server 块配置:

server {
    listen 80;
    server_name example.com;
    root /path/to/your/project;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php($|/) {
        fastcgi_pass   127.0.0.1:9000;  # 根据你的 PHP-FPM 配置调整
        fastcgi_index  index.php;

        # 关键 Pathinfo 配置
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO $fastcgi_path_info;

        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    }
}

详细说明

  1. 核心指令

    • fastcgi_split_path_info:将路径分割为脚本名和路径信息两部分
    • fastcgi_param PATH_INFO:设置 PATH_INFO 参数
  2. 常见问题解决

    • 如果出现 404 错误,检查 SCRIPT_FILENAME 是否正确指向 PHP 文件
    • 确保 PHP-FPM 配置中 cgi.fix_pathinfo=1(默认值)
  3. ThinkPHP 专用配置

location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php?s=$1 last;
        break;
    }
}
  1. Laravel 专用配置
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

安全注意事项

启用 pathinfo 可能存在安全风险,建议:

  1. 限制特定目录启用 pathinfo
  2. 确保 PHP 文件不会被直接访问
  3. 保持 Nginx 和 PHP 的及时更新

配置完成后,记得测试并重载 Nginx 配置:

nginx -t && nginx -s reload