Search code examples
apache.htaccessserver

How to make Apache .htaccess 404 addon domain subdomains/directories?


Forgive my inexperience with Apache, but I'm trying to set up my .htaccess file so that my 2 addon domains' subdomains and directories are inaccessible through the primary domain (i.e. they'll 404). In other words, addon-domain-1.primary-domain.com and primary-domain.com/addon-domain-1 should both be inaccessible.

I think I'm on the right track, but my current implementation doesn't work. Here's my code:

# Redirect to www/https
RewriteEngine on
RewriteCond %{HTTP_HOST} ^primary-domain\.com [NC]
RewriteRule ^(.*)$ https://www.primary-domain.com/$1 [R=301]

# Block addon domain directories
RewriteCond %{HTTP_HOST} ^addon-domain-1\.primary-domain\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^addon-domain-2\.primary-domain\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?primary-domain\.com [NC]
RewriteCond %{REQUEST_URI} ^/addon-domain-1/(.*) [OR]
RewriteCond %{REQUEST_URI} ^/addon-domain-2/(.*)
RewriteRule ^(.*)$ - [R=404,L]

This .htaccess file is placed in the root directory (primary-domain.com)

Thanks so much!


Solution

  • Ended up solving it by doing something similar to @anubhava's answer (with a few changes), and most importantly putting these changes inside the addon domains' .htaccess files as well.

    Primary domain:

    # Forward to www/HTTPS
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^primary-domain\.com [NC]
    RewriteRule ^(.*)$ https://www.primary-domain.com/$1 [R=301]
    
    # Block addon domain directories
    RewriteCond %{HTTP_HOST} ^(www\.)?(addon-domain-1|addon-domain-2)\.primary-domain\.com [NC,OR]
    RewriteCond %{REQUEST_URI} ^/(addon-domain-1|addon-domain-2)
    RewriteRule ^(.*)$ - [R=404,L]
    

    Addon domain 1:

    # Forward to www/HTTPS
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^addon-domain-1\.com [NC]
    RewriteRule ^(.*)$ https://www.addon-domain-1.com/$1 [R=301]
    
    # Block addon domain directories
    RewriteCond %{HTTP_HOST} ^(www\.)?addon-domain-1\.primary-domain\.com [NC,OR]
    RewriteCond %{REQUEST_URI} ^/addon-domain-1
    RewriteRule ^(.*)$ - [R=404,L]