在PHP中管理链接包括使用htaccess

Thanks for reading!

I am managing a header with links using a PHP include. It is within a folder /includes/header.php.

Here's an example of what header.php looks like:

<nav>
    <ul>
        <li><a href="index.php">Home</a></li>            
        <li><a href="page.php">Page</a></li>
    </ul>
</nav>

When I add the include to a file within the root directory, like /index.php, I add it like so: <?php include_once("header.php"); ?>. This all works fine, and the links point where they need to.

When I do the same thing but with a file in a subdirectory, for instance a file called /foo/page.php I will add the include like this: <?php include_once("../includes/header.php"); ?> - this way it grabs the file correctly.

My problem is that all of the links in the header.php file aren't going where I want them to. I found some information about using a set environment function in .htaccess, but I don't know what to make of it.

If you have an answer to this problem I'd love to hear it! Thanks!

Start all the links in the header from the root web directory.

Just do;

"/index.html"
"/subdirectory/link.html"

So basically just start all the links with a forward slash, as without it, it will look for the page within its current directory.

Store the base url of your application in a config file or database and then use it to build absolute links not relative ones. For example you have a file like config.php:

<?php
$baseUrl = "http://yourdomain/yourapp/";

And in header.php:

<?php include_once("config.php"); ?>
<a href="<?php echo $baseUrl; ?>page.php">Page</a>

It may seem inconvenient having to edit a file in case you move your application, but this way your links will work in any directory any time, and as your application grows there will be some other things like DB access that also have to be changed if you move your application, and can be stored in the same config file.

You can set the base url in your HTML head.