Ron van der Heijden
Ron van der Heijden

Reputation: 15080

Dynamically load images from css using htaccess in subfolder

I am creating multiple website in my local webserver. I have trouble when loading images form a css files dynamically when using subfolders.

This is my structure:

Root folder
    site1
        index.php (loads templates using Smarty)
        .htaccess
        public_files
            css
            js
            img
            templates

This is how my .htaccess looks like:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([a-zA-Z]+)$             index.php?uri=$1 [L]
RewriteRule ^(css|js|img)/(.*)$       public_files/$1/$2 [L]

Loading my css does work:

<link href="css/style.css" rel="stylesheet" />

But within this css I cannot load images

background-image: url("img/background.jpg");

I think this is because this line is called from the css folder. But when I use /img/... it will look in the root, which is also not the right place because I'm within a subfolder.

Upvotes: 1

Views: 828

Answers (2)

anubhava
anubhava

Reputation: 785481

Keep your site1/.htaccess like this:

RewriteEngine On
RewriteBase /site1/

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([a-zA-Z]+)$ index.php?uri=$1 [L]

RewriteCond %{SCRIPT_FILENAME} !-f    
RewriteCond %{REQUEST_URI} !/public_files/ [NC]
RewriteRule (?:^|/)css/(img/.+)$ public_files/$1 [L,NC]

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/public_files/ [NC]
RewriteRule (?:^|/)((?:css|js|img)/.+)$ public_files/$1 [L,NC]

Upvotes: 1

Phil Perry
Phil Perry

Reputation: 2130

url("img/background.jpg") says that img/ is relative to the directory holding the css (css/, I presume). So it could be looking in /css/img/. Try ../img/ instead.

Upvotes: 0

Related Questions