php - mod_rewrite trouble

647

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?

467

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).

518

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...

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

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:

RewriteLogLevel 3
RewriteLog "/path/to/a/file.log"
697

Answer

Solution:

2 simple ways

  1. absolutize the references as suggest by Ianzz
  2. 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.

People are also looking for solutions to the problem: javascript - Why is this XMLHTTPRequest aborted before going to the server?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.