问题
I have a common header.php to include in virtually every page of the website. I have relative links to different resources in the header.php file. As soon as I include it in other pages which are located in different sub-folders under the root folder, some of the links would break. I can make all the links in the header.php absolute. Now another problem pops up: If you move the application to another domain and put it somewhere under the wwwroot, the absolute links will not work. I couldn't find a way in PHP to extract the part of the URL which is the root for this application. I ended up define a variable for the application root and prefix every link inside header.php with this variable. This way, I only need to change one variable when this application is moved from one place to another.
I am wondering if there are other better ways to handle this kind of situation.
Your feed back would be much appreciated.
Edit: hoping to receive more feed back.
回答1:
You write it's a common header.php file, like with the central variable, you can do make use of the <base>
HTML element - but this is limited to HTML.
You can create yourself a mapping function that is able to resolved absolut URLS to the request URI, or that is able to resolved relative URLS to the context they come out of so that they can be mapped absolutely relatively to the request URI again.
Then you can implement a output filter that is handling URIs on it's own and you can do some special prefixes for special treatments.
来源:https://stackoverflow.com/questions/10197862/how-to-avoid-broken-links-in-common-header-file