简体   繁体   English

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

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

I have this in my htaccess:我的 htaccess 中有这个:

RewriteEngine on

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

and I have a PHP script that is redirecting to two directories /game/ or block/ I want to use curl to open files in one of the directories.我有一个 PHP 脚本,它重定向到两个目录 /game/ 或 block/ 我想使用 curl 打开其中一个目录中的文件。

This is my code for getting the URL:这是我获取 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();
}

The problem is that when I access the file locally for testing when I try to access:问题是当我在本地访问文件进行测试时,我尝试访问:

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

It got this URL:它得到了这个网址:

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

the PHP script and .htaccess file are located in: PHP 脚本和 .htaccess 文件位于:

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

how can I get the URL of the index.php the path where the .htaccess file is located?如何获取 index.php 的 URL 以及 .htaccess 文件所在的路径?

I need this to work as the root directory https://example.com/ the same as in any directory.我需要它作为根目录https://example.com/与任何目录一样工作。 I don't know where this script will be executed.我不知道这个脚本会在哪里执行。

Found the solution, first I was trying using htaccess:找到了解决方案,首先我尝试使用 htaccess:

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

but the script name was empty.但脚本名称为空。 But it turns out that the PHP variable:但事实证明 PHP 变量:

$_SERVER['SCRIPT_NAME']

Contain the URI of the php script.包含 php 脚本的 URI。 So I all have to do is to remove index.php:所以我要做的就是删除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