2013-12-19 29 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