RewriteRule to remove extraneous URL parts for pretty URLs
-
29-05-2021 - |
Вопрос
Background
Trying to recreate StackOverflow-style pretty URLs using Apache's mod rewrite and PHP.
Problem
This works great:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ([0-9]+)$ index.php?id=$1 [L]
</IfModule>
URLs like http://localhost/home/script/5
redirect to http://localhost/home/script/index.php?r=5
. The CSS content loads flawlessly.
URLs like http://24.68.226.186/recipes/recipe/5/seo-text
redirect, but the relative path for the CSS files is then incorrect:
<link rel="StyleSheet" hreF="css/theme.css" type="text/css" media="screen,print" id="css-theme" />
Directories
The directory structure for the script (index.php) resembles:
htdocs/home/script
htdocs/home/script/.htaccess
htdocs/home/script/index.php
htdocs/home/script/css
htdocs/home/script/images
Question
How do you use mod rewrite to tell Apache to use the "script" directory when serving files instead of any sub-directory appended to the URL?
In other words, how would you use mod rewrite to lop off the "seo-text" part of the URL and (1) ensure it reflects the actual title [sourced from a database]; (2) redirect the browser to the new URL [if necessary]; and (3) tell Apache to ignore all paths beyond the ID in the URL?
I would rather not use absolute paths in the CSS.
Thank you!
Решение
Used Logan's advice:
<base href="/home/script/" target="_self" />
This does not work with IE8, due to a bug.