Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache .htaccess: Serving .css files from separate domain?

I'm trying to serve CSS files for my site from a separate domain.

I've got the following entry in my site's .htaccess (in the document root):

RewriteRule ^templates/*\.css$ http://css.mysite.com/templates/$1 [R=301,L]

With the intention of simply matching:

http://www.mysite.com/templates/default/styles/main.css

… and sending an HTTP 301 redirect to:

http://css.mysite.com/templates/default/styles/main.css

But what's actually getting called is:

http://css.mysite.com/templates/.css

(I'd like to duplicate the above for *.js and serve them from js.mysite.com and all png & jpgs and serve them from img.mysite.com.)

Any insights would be fantastic. I've got to admit, htaccess rewrite rules always seem to elude me.

like image 422
gellenburg Avatar asked Feb 15 '12 00:02

gellenburg


1 Answers

Try this and let me know:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^css\.
RewriteRule ^templates/(.*)\.css$ http://css.mysite.com/templates/$1.css [R=301,L]

or a more "dynamic way"

RewriteCond %{HTTP_HOST} ^(www\.)?mysite
RewriteRule ^templates/(.*)\.(js|css)$ http://$2.mysite.com/templates/$1.$2 [R=301,L]
RewriteRule ^templates/(.*)\.(jpg|gif|swf|jpeg|png)$ http://imgs.mysite.com/templates/$1.$2 [R=301,L]

This one will check for JS and CSS and use the subdomain based on the file extension: so .js will go to js.mysite.com and .css will go to css.mysite.com and same for images but these goes to imgs.mysite.com instead.

or be even more generic:

RewriteCond %{HTTP_HOST} ^(www\.)?mysite
RewriteRule ^templates/(.*)$ http://media.mysite.com/templates/$1 [R=301,L]

You redirecting everything that start with templates

like image 191
Book Of Zeus Avatar answered Oct 20 '22 14:10

Book Of Zeus