Rewrite subdomain to main domain for images only u

2019-09-03 03:19发布

问题:

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]