Search code examples
javascriptcss.htaccesszend-framework2

Redirect css|js|img|fonts folder using .htaccess


I'm on shared hosting where some website live.

I have to move a ZendFramework2 on this server by adding it in a directory from the root (dir name = site). Controllers and actions are working right but I can't load any css, images or javascript.

Here are my directories :

/root/website1 (example.com/website1)
/root/website2 (example.com/website2)
/root/site     (example.com/site)
/root/site/application
/root/site/data
/root/site/library
/root/site/public
/root/site/public/css
/root/site/public/fonts
/root/site/public/img
/root/site/public/js
/root/site/public/.htaccess
/root/site/.htaccess

.htacces in /site folder

RewriteEngine On

RewriteRule ^\.htaccess$ - [F]

RewriteCond %{REQUEST_URI} =""
RewriteRule ^.*$ /site/public/index.php [NC,L]

RewriteCond %{REQUEST_URI} !^/site/public/.*$
RewriteRule ^(.*)$ /site/public/$1

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [NC,L]

RewriteRule ^site/public/.*$ /site/public/index.php [NC,L]

.htacces in /site/public folder

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ /site/index.php [NC,L]

css tag :

<link href="/css/global.css" rel="stylesheet" type="text/css" media="screen" />

Can i redirect /css/global.css to load /site/public/css/global.css ?

Sure, i could change for ...

<link href="/site/css/global.css" rel="stylesheet" type="text/css" media="screen" />

... but i prefer not to change href

Any help is very welcome!


Solution

  • I would create only one .htaccess file to solve all your problems. Please put this into your /root folder and delete the other .htaccess files.

    # This first part should be done by the webserver,
    # if not than thing about to change you hoster but I put it here:
    # Preventing direct access to any .ht file (.htaccess, .htpasswd, etc.)
    <FilesMatch "^\.ht">
        Require all denied
    </FilesMatch>
    
    Options +FollowSymlinks
    Options -Indexes
    
    # Start to Rewrite
    RewriteEngine On
    
    # For all URL starting with /css, /fonts, /img or /js
    RewriteCond %{REQUEST_URI} ^/?(css|fonts|img|js)(/.*)?$ [NC]
    RewriteRule ^.*$ /site/public/%1%2 [L]
    
    # Redirect all to the Application if not done already
    RewriteCond %{REQUEST_URI} !^/?site/public/index\.php [NC]
    # but not if the URL starts with css, fonts, img or js
    RewriteCond %{REQUEST_URI} !^/?(css|fonts|img|js)(/.*)?$ [NC]
    # or if request is a real file
    RewriteCond %{REQUEST_FILENAME} !-f
    # or if request is a real directory but not the root directory
    RewriteCond %{REQUEST_URI} ^/?$ [OR]
    RewriteCond %{REQUEST_FILENAME} !-d
    # Rewrite the rest to the index.php file in your public folder
    RewriteRule ^.*$ /site/public/index.php [NC,L]