Apache .htaccess : Serving . css 文件来自单独的域?

标签 apache .htaccess mod-rewrite

我正在尝试从单独的域为我的网站提供 CSS 文件。

我的网站的 .htaccess(文档根目录中)中有以下条目:

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

为了简单地匹配:

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

…并将 HTTP 301 重定向发送至:

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

但实际被调用的是:

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

(我想为 *.js 复制上述内容,并从 js.mysite.com 提供它们,所有 png 和 jpg 并从 img.mysite.com 提供它们。)

任何见解都会很棒。我必须承认,htaccess 重写规则似乎总是让我困惑。

最佳答案

试试这个并让我知道:

RewriteEngine On
RewriteBase /

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

或更“动态的方式”

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]

这将检查 JS 和 CSS,并根据文件扩展名使用子域:因此 .js 将转到 js.mysite.com,.css 将转到 css.mysite.com,图像也是如此,但这些是改为 imgs.mysite.com。

或者更通用:

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

您重定向以 templates 开头的所有内容

关于Apache .htaccess : Serving . css 文件来自单独的域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9286226/

相关文章:

php - Slim 框架报错 apache

php - 允许 artisan 服务中的 cors

.htaccess - 是否有一个 Nginx 环境变量相当于 Apaches 的 {ENV :REDIRECT_STATUS}?

.htaccess - 重写url问题

regex - 在 htaccess RewriteRule 中排除特定子域或无子域

apache - 如何从 Apache URL 重写条件中排除子目录

php - IP 地理位置与 Mod_Rewrite & PHP

php - 从 wp-content .htaccess 中排除特定的 php 文件

php - .htaccess url-rewrite 如果文件不存在 - 如何处理 favicon.ico?

.htaccess - 重写不适用于 ssl