I have a custom PHP framework in which everything after the domain is sent to PHP as a $_GET variable, like so:
RewriteRule ^(.*)$ index.php?page_request=$1 [QSA,L]
All routing is done by a router file. For example, http://domain.tld/page
gets sent to http://domain.tld?page_request=home
.
However, if I have a directory-like structure (i.e. http://domain.tld/page/
), the request is sent, but any relative URLs in the HTML are now relative to /page
, even though we're still in the root level in the domain.
To clarify:
Going to http://domain.tld/page
and requesting res/css/style.css
in HTML returns a stylesheet.
Going to http://domain.tld/page/
and requesting res/css/style.css
returns an 404 error, because the page/
directory doesn't actually exist.
What's the best way to work around this? This seems really simple, but I'm not quite good enough with .htaccess yet to do it off the top of my head. Thanks for any answers in advance.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
However, I can't do that with this particular website, because it's a subfolder on a server, so linking to /
would go to the root of the server and not the site.
If I put /subfolder/css
for every link on the site, that would not only get tedious, but also problematic were the subfolder to change. Is there a better way to work around this?
The other answers that say you have to absolutize the paths are correct. If you are working in a subfolder, there are two things that you can/should do to help:
1) Use RewriteBase
in your htaccess file
RewriteEngine on
RewriteBase /framework/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/?$ index.php?url=$1 [QSA,L]
2) Create a constant in your framework that has that same path
define('FULL_PATH', '/framework');
Then each time you create a URL in html, make sure you do something like
<a href="<?= FULL_PATH ?>/your/remaining/path">
It's a little bit of extra work to think about this each time you create a URL on the page, but it will serve you well in the long run.
Relative URLs are not affected by apache rewrite rules. They're up to the browser. If the browser sends a request for /some/random/path/
, you can rewrite it all you want on the server end, but the browser will interpret all relative urls as being inside /some/random/path/
If you want to include res/css/style.css
from the root, you should prefix it with a leading slash to make that clear: /res/css/style.css
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With