简体   繁体   中英

Block access to all but a single URI with htaccess from a subdomain

I'm trying to use htaccess to prevent access to my site unless the requests are going to a specific URI, but only when accessed from a certain subdomain.

Essentially I've a number of subdomains which I am using to get around browser request limits to speed up the loading of a page with has many images. I've tested and this is working well, preventing the browser from blocking requests until others have finished.

What I want to achieve is blocking access to the rest of the site from these subdomains, so they can only access URIs starting with /images . The idea being to avoid duplicate URLs for my pages or a subdomain accidentally being indexed in Google.

Try as I have, I cannot get it right, here is what I have so far:

<IfModule mod_rewrite.c>

    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Prevent access to anything but the /images URI from subdomains
    RewriteCond %{HTTP_HOST} ^cdn[1-9]\.domain.localhost$ [NC]
    RewriteRule !^/images.* - [R=404]

</IfModule>

The URI I would like the subdomains to access is:

domain.localhost/images/(products|retailers)/400/400/filename.jpg

As you may have guessed that is not a physical folder structure, its a route within my Laravel PHP application.

From my understanding the bottom rule should should be saying "If the request is from a matching domain, and the request URI does not begin with /images redirect to a 404 error but as it does not work I must be pretty far off the mark. I believe the issue could be due to the order of the rules but I'm unsure.

Any suggestions?

The RewriteRule directive receives the URI on a per directory basis. So, the path it receives would not contain the leading slash ( / ). That is only accessible for rewrites done in either the server or vhost context.

I'd suggest you use the %{REQUEST_URI} variable instead for you rule:

RewriteCond %{HTTP_HOST} ^cdn[1-9]\.domain\.localhost$ [NC]
RewriteCond %{REQUEST_URI} !^/images\b [NC]
RewriteRule ^ - [R=404]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM