PHP内置服务器和.htaccess mod重写

Mar*_*tyn 26 php .htaccess php-5.4

PHP的内置服务器不使用.htaccess吗?有道理我认为因为它不依赖于Apache(?).无论如何,有可能告诉服务器使用这些文件,它能处理URL重写吗?我在框架中有一些依赖于这些文件的项目.

APPLICATION_ENV=development php -S localhost:8000 -t public/

Cal*_*leb 27

这是我用于内置php网络服务器的路由器,如果文件系统存在,则为文件系统提供资源,否则会对index.php文件执行重写.

运行使用:

php -S localhost:8080 router.php
Run Code Online (Sandbox Code Playgroud)

router.php:

<?php

chdir(__DIR__);
$filePath = realpath(ltrim($_SERVER["REQUEST_URI"], '/'));
if ($filePath && is_dir($filePath)){
    // attempt to find an index file
    foreach (['index.php', 'index.html'] as $indexFile){
        if ($filePath = realpath($filePath . DIRECTORY_SEPARATOR . $indexFile)){
            break;
        }
    }
}
if ($filePath && is_file($filePath)) {
    // 1. check that file is not outside of this directory for security
    // 2. check for circular reference to router.php
    // 3. don't serve dotfiles
    if (strpos($filePath, __DIR__ . DIRECTORY_SEPARATOR) === 0 &&
        $filePath != __DIR__ . DIRECTORY_SEPARATOR . 'router.php' &&
        substr(basename($filePath), 0, 1) != '.'
    ) {
        if (strtolower(substr($filePath, -4)) == '.php') {
            // php file; serve through interpreter
            include $filePath;
        } else {
            // asset file; serve from filesystem
            return false;
        }
    } else {
        // disallowed file
        header("HTTP/1.1 404 Not Found");
        echo "404 Not Found";
    }
} else {
    // rewrite to our index file
    include __DIR__ . DIRECTORY_SEPARATOR . 'index.php';
}
Run Code Online (Sandbox Code Playgroud)

  • 在测试时,我使用它而不是创建一个全新的 Apache 虚拟主机。非常有用的片段。 (3认同)

Aga*_*res 12

使用PHP内置的webserver无法处理.htaccess(它不依赖于apache,它是在PHP的核心中实现的).但是,您可以使用路由器脚本(在此处描述:http://php.net/manual/en/features.commandline.webserver.php).

例如 php -S localhost -S localhost:8080 router.php

  • 您不能将.htaccess与PHP的内置服务器一起使用.它不受支持.如果你想使用.htaccess而不是其他方式来配置你的web服务器,你要么必须使用Apache,要么自己在PHP中解析.htaccess(这可能是一件困难的事情) (2认同)