Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative URLs with .htaccess

Tags:

php

.htaccess

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.

Edit: Also, my .htaccess file contains:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

Edit #2: Yes, I know about using the leading /.

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?

like image 821
element119 Avatar asked Sep 30 '11 21:09

element119


2 Answers

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.

like image 77
Andrew Avatar answered Sep 23 '22 15:09

Andrew


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

like image 36
Frank Farmer Avatar answered Sep 26 '22 15:09

Frank Farmer