热搜:NVER node 开发 php

PHP 重写读取文件,适用多域名的情况!

2024-08-16 15:25:01
PHP 重写读取文件,适用多域名的情况!

如果一个网站同一套程序绑定了多个域名 www.a.com ,www.b.com,为了区分他们的robots.txt、百度站长验证文件等,如 www.a.com/robos.txt 的内容来自于 /Virtual/www.a.com/robots.txt www.b.com/robots.txt 的内容来自于 /Virtual/www.b.com/robots.txt 的方法:
RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^([a-zA-Z0-9_]{2,32}\.(xml|html|txt)) seo.php?file=$1 [L]

文件 /seo.php
<?php /** * @param string $msg */function _404($msg = ''){    header('HTTP/1.1 404 Not Found');    header('Status: 404 Not Found ');    // 确保FastCGI模式下正常    if (empty($msg)) $msg = ' 404 Not Found. ';    exit($msg);}function getExt($file){    return strrchr($file, '.');}$file = trim($_GET['file']);if (!preg_match('/^[a-zA-Z0-9_]{3,32}\.(html|txt|xml)$/i', $file)) _404();$dir = 'Virtual/' . strtolower($_SERVER['HTTP_HOST']);if (!is_dir($dir)) _404();$filePath = $dir . '/' . $file;if (file_exists($filePath) && is_file($filePath)) {    switch (getExt($file)) {        case '.txt':            $type = 'text/plain; charset=UTF-8';            break;        case '.xml':            $type = 'application/xml';            break;        case '.html':        default:            $type = 'text/html; charset=UTF-8';            break;    }    if (!empty($type)) {        header('Content-type:' . $type);    }    echo file_get_contents($filePath);} else {    _404();}