Simon Josef Kok
Simon Josef Kok

Reputation: 795

Basic URL rewriting: How to have a css link, img src, etc, ignore it?

I have a website running at localhost/pm and the RewriteBase is correctly set to /pm/. There is a link tag in my document: <link ... href="themes/default/css/default.css">.

When the url is localhost/pm or localhost/pm/foo the CSS works all right. When there are more slashes in the URL, however, like localhost/pm/foo/bar the relative URL if the stylesheet changes to foo/themes/default/css/default.css.

How do I get this to work without having to put some sort of PHP path resolution in the link tag?

# invoke rewrite engine
RewriteEngine On
RewriteBase /pm/

# Protect application and system files from being viewed
RewriteRule ^(?:system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

EDIT:

Basically what I need now is this: If request contains folder name /themes/ scrap everything that is before /themes/ and rewrite the rest to /pm/themes/...

I tried it like this: RewriteRule ^.*(/themes/.*)$ /pm/themes/$1 but I get an internal server error. Why?

If I do it like this: RewriteRule ^.*(/themes/.*)$ /pm/themes/ (ie. just remove $1 from the end) and use the URL http://localhost/pm/foo/themes/foo/ the resulting physical location is http://localhost/pm/themes which is what is expected too, which in turn means that at least my regex is correct. What am I missing?

Upvotes: 1

Views: 1436

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74058

The RewriteRule is almost correct

RewriteRule ^.*(/themes/.*)$ /pm/themes/$1

This rewrites http://localhost/pm/foo/themes/default/css/default.css to http://localhost/pm/themes/themes/default/css/default.css, which is one themes too much. Use this instead

RewriteRule /themes/(.*)$ /pm/themes/$1 [L]

But now you have an endless rewrite loop, because /pm/themes/.. is rewritten again and again. To prevent this, you need a RewriteCond excluding /pm/themes

RewriteCond %{REQUEST_URI} !^/pm/themes/
RewriteRule /themes/(.*)$ /pm/themes/$1 [L]

Now the request is rewritten only once and you're done.

Upvotes: 1

Will Warren
Will Warren

Reputation: 1294

You probably need to add the following lines before your RewriteRule:

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

It will only evaluate your rewrite rule if the requested file or directory doesn't exist.

You should post your .htaccess file so we can offer better advice

Upvotes: 0

Related Questions