Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod Rewrite path issues

I have successfully created rewrite rules to handle URLs like

http://example.com/xyz

http://example.com/xyz/

http://example.com/xyz/abc

http://example.com/xyz/abc/

Here is the mod rewrite & regex:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

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

RewriteRule ^/?([0-9]+)(?:\/)?$ /index.php?p=$1 [L]
RewriteRule ^/?([-a-zA-Z0-9_+]+)(?:\/)?$ /index.php?n=$1 [L]
RewriteRule ^/?([-a-zA-Z0-9_+]+)/([-a-zA-Z0-9_+]+)(?:\/)?$ /index.php?n=$2 [L]

This works great, but the problem is that when I go to http://example.com/xyz/abc, my script gets the correct input (n=abc) but the paths are messed up, so all relative URLs in my code are broken, as they are now relative to xyz instead of the root.

Is there a way around this at all? As you can see above I have tried to redirect to /index.php to force the path to be correct. My brain is fried after a long day of regex and code, so I hope it's not something disastrously trivial.

like image 967
Antony Carthy Avatar asked Dec 02 '22 06:12

Antony Carthy


1 Answers

Use the HTML base element to force all relative URLs to use a different path than the one the browser displays.

<base href="http://www.example.com/"/>
...
<a href="relative/url">link</a>

The relative URL will use "http://www.example.com" as its base, even if the browser thinks it's looking at the page "http://www.example.com/xyz/". So the link goes to "http://www.example.com/relative/url" instead of "http://www.example.com/xyz/relative/url"

And there's the Stack Overflow way of doing it, in which every URL is either an absolute path (to resources like images) or paths including the root (i.e. "/feeds/questions/123"), which avoid the relative path issues.

like image 65
Welbog Avatar answered Dec 04 '22 01:12

Welbog