Dynamic URLs in CSS/JS

2019-03-15 06:17发布

I'm splitting up one of my larger apps and introducing a 'cdn' url to house common objects like CSS, javascript, and images to avoid duplication. What I need to do, though, is have separate URLs for our dev environments, so I may have:

http://cdn-dev.example.com
http://cdn-qua.example.com
http://cdn.example.com

depending on what environment we're working in. I can get this to work for things that are generated by our PHP code, but I'm at a loss for the .css and .js files that will be called. For example, how do I make something like:

.cool-button { background-image: url('http://cdn.example.com/images/button.png'); }

switch between the different domains?

What's the best way to deal with that?

[EDIT]

Just so everyone is clear, the CDN address is a different domain that the site. So, the dev site might be http://www-dev.domain.com which would use http://cdn-dev.domain.com

9条回答
Deceive 欺骗
2楼-- · 2019-03-15 07:16

I've literally just been working on the same thing today and here's what I came up with.

Stick this in your .htaccess file in the root of your site. This obviously relies on Apache and Mod_rewrite.

RewriteEngine on
RewriteBase /

# Redirect content to the CDN

RewriteCond %{HTTP_HOST} !^cdn\.server\.com$    [NC]
RewriteRule .*\.(jpg|gif|png|flv|css|js|swf)$   http://cdn.server.com/$0    [R=301,L]

This will send requests for the file types in the brackets to your cdn and keep requests for other types on your primary server.

查看更多
仙女界的扛把子
3楼-- · 2019-03-15 07:20

Just use domain-relative url's?

.cool-button { background-image: url('/images/button.png'); }

Then the browser will look under the current domain.

查看更多
聊天终结者
4楼-- · 2019-03-15 07:20

Depending on your server configuration, you can also append the .php-extension to your filenames and have them treated as PHP scripts too:

I.E.: style.css.php would contain:

.cool-button { background-image url(<?php echo $bgImgUrl;?>); }

This also works for JavaScript-files.

查看更多
登录 后发表回答