user3143218
user3143218

Reputation: 1816

htaccess rewriting specific folder/path to subdomain

I'm trying to setup a redirect for a site.

I want rewrite file requests from a folder to a subdomain url.

At the moment, I have this in my htaccess:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{HTTP_HOST} !^example.com
RewriteCond %{HTTP_HOST} ^g.example.com
RewriteRule ^(uploads/(.*)+ uploads/%1%{REQUEST_URI} [L]

The idea is that when a visitor requests:

http://g.example.com/uploads/somefile.png

they are served:

http://example.com/uploads/somefile.png

So it's working as expected. However the problem is that:

http://b.example.com/uploads/somefile.png

also works.

I only want http://g.example.com/ to be rewritten. http://b.example.com/ should 404.

Upvotes: 0

Views: 59

Answers (1)

Prix
Prix

Reputation: 19528

This should work:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^g.example.com$ [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*)\.(JPG|GIF|PNG) [NC]
RewriteRule ^ - [R=404,L]

RewriteCond %{HTTP_HOST} ^g.example.com$ [NC]
RewriteCond %{THE_REQUEST} !^GET [NC]
RewriteRule ^ - [R=404,L]

The first rule will make sure that any URL ending with JPG, GIF, PNG that does not come from g.example.com send a 404 not found request to the user.

The second rule makes sure that g.example.com are only accessed using GET requests.

Upvotes: 1

Related Questions