Rewrite subdomain to main domain for images only using htaccess

给你一囗甜甜゛ 提交于 2019-12-13 06:27:03

问题


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.

Thanks

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]

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


回答1:


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 example in /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]


And in /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

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]


来源:https://stackoverflow.com/questions/20677792/rewrite-subdomain-to-main-domain-for-images-only-using-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!