• 0

Url Rewrite and relative file paths


Question

I'm using .htaccess to rewrite my urls so "index.php?p=something" can be written as "pages/something" or "pages/something/" instead. (with or without the trailing / )

My .htaccess file:

RewriteEngine on
RewriteRule ^page/(.+?)/?$ index.php?p=$1

Problem is that I link relatively to files (css and other) from the pages that gets their url rewritten.

The browser obviously believes that the files are relative to "/pages/something/" but those folders doesn't exist.

I would really like to avoid linking to files with their absolute paths (horror while developing locally and testing on the real web-server) so what should I do so the browser still get the correct files?

Do I have to rewrite the rewritten url back again if it links to files (maybe if there is a dot(.) in the path?)

Link to comment
https://www.neowin.net/forum/topic/658080-url-rewrite-and-relative-file-paths/
Share on other sites

5 answers to this question

Recommended Posts

  • 0

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^pages/([a-z0-9\-]+)([/]?)$  /index.php?p=$1

This rule will check if the file or folder exist first and if they don't it will do the rewrite.

  • 0

TurboTuna:

Thanks for your reply, but as I said I cannot always navigate to the root with absolute paths because my website isn't located at the root of my development server so images and such wouldn't show up in my browser while developing.

Gerry:

Thanks, that is very nice to know :) However it doesn't prevent my browser to try to look for the files in folders that doesn't exist. When looking at mydomain.com/pages/info/ it would look for the relative files in mydomain.com/pages/info/styles/css.css instead of mydomain.com/styles/css.css

I'm guessing I have to make a counter-rewrite for all paths that doesn't include a dot indicating a filename, but that looks like a pretty error-prone solution to me. Am I missing something?

Thanks :-)

  • 0
However it doesn't prevent my browser to try to look for the files in folders that doesn't exist. When looking at mydomain.com/pages/info/ it would look for the relative files in mydomain.com/pages/info/styles/css.css instead of mydomain.com/styles/css.css

Thats normal, and thats got nothing to do with the rewrite rule. Just add the full address when getting images and css, or use "/" and use subdomain.

  • 0
Thats normal, and thats got nothing to do with the rewrite rule. Just add the full address when getting images and css, or use "/" and use subdomain.

(Y) There's no workaround other than to stop using the rewrite rule, or do what Gerry says.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.