Search code examples
angularapache.htaccessangular-router

Apache wildcard subdomain rewrite with Angular app


I have an Angular app that needs to run under a subdomain for multi-tenant support. Every subdomain is a different tenant under the app. For now I have current .htaccess setup that does the work for (only) loading the main page, but actual Angular routing does not work at all.

Current .htaccess looks like this:

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

RewriteEngine On
RewriteBase /manager
RewriteCond %{HTTP_HOST} !^www\.domain\.io
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.io [NC]
RewriteCond %{REQUEST_URI} !manager/
RewriteRule (.*) /manager/%{REQUEST_URI} [L]

There is also a WP site on the main domain, hence the WordPress entries.

What I want to achieve is whenever someone goes to SUBDOMAIN.domain.io it loads the files from /manager folder without rewriting address and then allows for angular routing to work, so when someone goes to subdomain.domain.io/admin it will load the angular route.

Is this possible? If yes, then could someone suggest a solution? Thanks!


Solution

  • Your complete .htaccess may work like this:

    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{HTTP_HOST} ^(?!www\.)[^.]+\.domain\.io$ [NC]
    RewriteRule !^manager/ manager%{REQUEST_URI} [L,NC]
    
    RewriteRule ^(index\.php$|manager/) - [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
    

    It is important to place manager rule before WP front controller rule.

    • (?!www\.) is a negative lookahead that fails the match if host name start with www..

    • RewriteRule !^manager/ manager/%{REQUEST_URI} [L,NC] will execute only if URI doesn't start with /manager/