简体   繁体   中英

A way to get relative paths to work using subdomains?

When accessing a page through a subdomain, all includes and relative paths break (even though the directory structure on the server should allow for the relative path to find it). What's the best way to have files on multiple subdomains access central resources (without using absolute paths)?

An JavaScript example:

m_url : '../code/php/UserAPI.php',

    $.ajax({
        url: someClass.m_url,
        dataType: "json",
        data: paras,
        success: function(ret){someClass.onLoggedIn(ret, callback)}
    });

if this UserAPI is called from subdomain1.example.com and subdomain2.example.com but the php resides on example.com how can one make the relative path follow the linux directory structure instead of adding trying to concatenate the subdomain/domain path?

ps. The reason m_url can't be hard coded is because the code has to work on both development and production servers.

Thanks as always!!

You could use the $_SERVER['PATH_TRANSLATED'] to determine the current position based on filesystem and then go relative to that. However, it would require some tweaking to the Apache setup .

Perhaps an alternate solution would be to sense via $_SERVER what host you're on (Dev, Prod, etc) and define those paths as needed. Then, just set your prefix before defining path. Sure, it requires a few extra lines of code, but it cuts the brain damage in half. That strategy has been used in many large production environments I've worked in.

As bpeterson76 answered, $_SERVER['PATH_TRANSLATED'] and $_SERVER['SCRIPT_FILENAME'] will you give the raw server path of the script, which you can then adjust depending on your subdomain structure.

These server variables aren't always available, so you could instead use the PHP function getcwd() - this will return the directory of the script without the filename. Then adjust as above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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