Daniel Oakey
Daniel Oakey

Reputation: 425

How can I avoid this error with mod_rewrite?

I have a site running on XAMPP on Windows. The root of the site is at localhost/sitename/.

I've used .htaccess with mod_rewrite to make index.php?app=appname appear at either sitename/appname/ or sitename/appname.

When I access an app through sitename/appname (without trailing slash), everything is fine. The browser finds my images and css at sitename/assets/.., as they are found relative to the current page.

The problem is, when I access an app through sitename/appname/ (with trailing slash), the browser cannot find my assets folder, as it is now trying to look in sitename/appname/assets/.

Without mod rewriting the assets folder, what can I do to fix this?

Upvotes: 1

Views: 91

Answers (3)

Daniel Oakey
Daniel Oakey

Reputation: 425

Looking at how WordPress handles this problem when posts are viewed at index.php with address www.example.com/permalink-to-post/, it seems the best answer is to use absolute file paths to all links, images and CSS.

In this case, each link to the /assets/ folder should be http://localhost/sitename/assets/. (Until the site is on a live web server)

Upvotes: 0

Jon Lin
Jon Lin

Reputation: 143886

The problem is, when I access an app through sitename/appname/ (with trailing slash), the browser cannot find my assets folder, as it is now trying to look in sitename/appname/assets/.

The trailing slash is changing the base of your relative URI's. Without using mod_rewrite voodoo to fix this, you need to add the correct base in your page headers using the <base> tag:

<base href="/sitename/appname/">

or whatever the appropriate base should be.

Upvotes: 2

Bobulous
Bobulous

Reputation: 13169

I'm guessing that without the slash your browser thinks that the current directory is /sitename/ and that with the slash your browser thinks the current directory is /sitename/appname/.

So any asset with a relative path (not beginning with a forward-slash) such as "assets/image.png" will be assumed to be based in the current directory. To fix this you can either change all asset paths to an absolute path anchored to the root by starting the path with a forward-slash, so the previous example would become "/sitename/assets/image.png". But I think, despite your desire to avoid a rewrite for the assets path, the following is simpler:

RewriteRule ^/sitename/appname/assets/(.+)$ /sitename/assets/$1

This will catch any lost requests for the non-existent appname/assets path and refer them to the correct /sitename/assets path.

Upvotes: 1

Related Questions