繁体   English   中英

如何在不更改 URL 的 htaccess 重定向后获取 PHP 文件的基本 URL

[英]How to get base URL of PHP file after htaccess redirect that doesn't change the URL

我的 htaccess 中有这个:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

我有一个 PHP 脚本,它重定向到两个目录 /game/ 或 block/ 我想使用 curl 打开其中一个目录中的文件。

这是我获取 URL 的代码:

function is_https() {
    // apache
    if (isset($_SERVER['HTTPS'])) {
        return true;
    }
    // heroku
    if (isset($_SERVER['HTTP_X_FORWARDED_PORT']) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
        return $_SERVER['HTTP_X_FORWARDED_PORT'] == 443 || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
    }
    return false;
}

function get_self() {
    return 'http' . (is_https() ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

function main() {

    $addresses = json_decode(file_get_contents('ip.json'));
    $blocked = in_array($_SERVER['REMOTE_ADDR'], $addresses);
    $url = get_self() . ($blocked ? "/block/" : "/game/");
    $url .= $_GET['q'];
    
    echo $url;
}

if (isset($_GET['q'])) {
    main();
}

问题是当我在本地访问文件进行测试时,我尝试访问:

http://localhost/~kuba/jcubic/support/order/app/index.js

它得到了这个网址:

http://localhost/~kuba/jcubic/support/order/app/index.js/game/index.js

PHP 脚本和 .htaccess 文件位于:

http://localhost/~kuba/jcubic/support/order/app/

如何获取 index.php 的 URL 以及 .htaccess 文件所在的路径?

我需要它作为根目录https://example.com/与任何目录一样工作。 我不知道这个脚本会在哪里执行。

找到了解决方案,首先我尝试使用 htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1&f=%{SCRIPT_NAME} [L,QSA]

但脚本名称为空。 但事实证明 PHP 变量:

$_SERVER['SCRIPT_NAME']

包含 php 脚本的 URI。 所以我要做的就是删除index.php:

function get_self() {
    $uri = preg_replace("/index.php$/", "", $_SERVER['SCRIPT_NAME']);
    return 'http' . (is_https() ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $uri;
}
// is_https is in the question

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM