php - mod_rewrite trouble
So I'm using a simple rewrite rule like:
RewriteEngine On
RewriteRule ^foo/?$ foo.php [NC,L]
It redirects perfectly to foo.php, but it seems like all links and images in foo.php are being taken from folder foo on the server which doesn't exist. For instance, 1.png will now be foo/1.png or index.html will now be foo/index.html. So my question is: is there any way to make thing right without changing paths to the files in foo.php?
Answer
Solution:
Your visitors' browsers see the current page as being at
/foo/
, thus all relative URLs will be resolved under/foo/
. You will need to set the base URL, or update all your relative URLs to point to your site root (e.g. do not userelative/path/url.jpg
but/relative/path/url.jpg
).Answer
Solution:
In your code you should provide a rewrite rule for your resources (images, css, etc...) or add conditions for real files / folders like...
The two RewriteCond lines test to see if the requested URL points to an actual real directory (the !-d part), and the second one tests if it's a real file (!-f)
In the future, you can easily debug your mod_rewrite stuff by adding this two lines to your .htaccess file:
Answer
Solution:
2 simple ways
remove the foo path for referenced object still using htaccess
RewriteRule ^foo(/.*.(jpg|html|gif|css))$ $1 [L]
I prefer the 2nd solution because the htaccess do the mess and htaccess fix the situation, and no changes to your code are needed.