我正在尝试从单独的域为我的网站提供 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/