仅使用htaccess将子域重写为主域以获取图像 [英] Rewrite subdomain to main domain for images only using htaccess

查看:199
本文介绍了仅使用htaccess将子域重写为主域以获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个域名,除了image \css等之外的所有内容都由一个php文件处理。但是,在重组之后,很多图像已经从子域移动到主域。所以我正在寻找一种方法将所有image \ css文件重定向到主域,如果它们最初位于其中一个子域上的话。我当前的代码是

I have a domain, where everything except image\css etc. are handled by a single php file. However after a reorganisation, alot of images have been moved from sub-domains to the main domain. So I'm looking for a way to redirect all image\css files to the main domain if they were originally on one of the sub-domains. My current code is

RewriteEngine On
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.ico|\.bmp|\.css|\.ts|\.js)$
RewriteRule !^index\.php$ /index.php [L]

我尝试了几种方法来重定向它,但是我似乎打破了现有的规则,无论我尝试什么。

I've tried a couple of ways to redirect it, but I seem to break on of the existing rules, whatever I try.

谢谢

我提出的最终解决方案with

The final solution I came up with

RewriteEngine On
# Check the request isn't for the main domain
RewriteCond %{HTTP_HOST} !^domain\.com$
# Check the request is for a static resource
RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
# Redirect to main domain
RewriteRule (.*) http://domain\.com/$1 [R=301,L]
# if the request isn't for index.php,
# (invisibly) redirect to index.php
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.ico|\.bmp|\.css|\.ts|\.js)$
RewriteRule !^index\.php$ /index.php [L]

仅供参考。至于jon的答案,我只是根据我的需要调整它。

For information only. As really the credit goes to jon for the answer I just tweaked it for my needs.

推荐答案

如果你的HTML中的网址仍然存在指向子域,您需要在这些子域上设置htaccess重定向,而不是在主域上,因为请求仍将转到子域。

If the URLs in your HTML still point to the subdomains, you'll need to setup htaccess redirects on those subdomains, not on the main domain, as the requests will still be going to the subdomains.

For例如 /var/www/vhosts/sub.domain.com/httpdocs/.htaccess

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
RewriteRule (.*) http://domain.com/$1 [R=301,L]



/var/www/vhosts/sub2.domain.com/httpdocs/.htaccess

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
RewriteRule (.*) http://domain.com/$1 [R=301,L]

更新

根据您对Apache的评论处理每个子域,就好像它是主子域一样,试试这个:

Based on your comment that Apache handles each subdomain as if it were the main one, try this:

RewriteEngine On
# Check the request isn't for the main domain
RewriteCond %{HTTP_HOST} !(www\.)?domain\.com$
# Check the request is for a static resource
RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
# Redirect to main domain
RewriteRule (.*) http://domain.com/$1 [R=301,L]

这篇关于仅使用htaccess将子域重写为主域以获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆