简体   繁体   中英

Rewrite rules and base url

When one uses a rewrite rule, say:

RewriteRule ^foo/(.+?)/?$ index.php?type=foo&value=$1 [NC,L]

The client still sees this as a url server.dom/foo/bar/ (it has no knowledge how these url's are resolved internally, which is of course reasonable).

If the page index.php however generate a link ( <a href="baz">link</a> ), the client will interpret this as server.dom/foo/bar/baz . index.php however has in many cases no full knowledge about where the url originates from...

A first idea was to pass the depth of the "virtual" path as a parameter. Thus the rewrite rule would be something like:

RewriteRule ^foo/(.+?)/?$ index.php?type=foo&depth=2&value=$1 [NC,L]

As a result, index.php should write:

<base href="../../">

Or more formally depth times .. (separated by slashes). In some cases, however, .htaccess has no knowledge about the depth of the "virtual" path as well. Furthermore one can note that the last slash ( / ) in the rewrite rule is optional, depending on whether the slash was written down, the depth varies. This would increase the number of RewriteRules significantly...

What are good/better practices to resolve this relative links problem robustly (robust perhaps in the sense that moving parts of the website will not "break" the links)?

If you're using pretty links I would strongly suggest not use relative links. You can use links as:

<a href="<?php base(); ?>baz">link</a>

where base() function is defined in some config.php to output /foo/ .

That way link will resolve to /foo/baz instead of /foo/bar/baz . If you have to move your website to some other path just update your base() function inside your config.php . This is same as what many CMS frameworks do like Wordpress or CakePHP.

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