2013-12-19 28 views
0

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

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

我已经尝试了几种方法来重定向,但我似乎对现有的规则,无论我尝试打破。

感谢

我想出了

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] 

仅用于信息的最终解决方案。诚然,为了答案,我只是根据自己的需要调整了它。

回答

1

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

例如在/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] 

UPDATE

基于您的评论阿帕奇处理每个子就好像它是在主要的一个,试试这个:

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] 
+0

谢谢,这将工作,但我错过了一个关键的细节(对不起我的错)我已经安装了Apache,以便它处理所有子域,就好像它们是主域。所以在短期内图像仍然有效,但从长远来看,我想重定向它们,以便搜索引擎等停止寻找子域。 – dragonfly

+0

刚刚更新了我的答案以反映这一点。 – Jon

+0

刚做完检查,图像没有被重定向正确。我用正确的域名取代了domain.com的两个引用,然后将其粘贴在我以前的代码上面。 (所以页面仍然会重定向到index.php),我也离开了第一个domain.com中的\不知道它是否是正则表达式的一部分。只是为了澄清我想要jon.blog.com \ fred \ test.jpg重定向到blog.com \ fred \ test.jpg – dragonfly