Search code examples
apache.htaccessmod-rewriteurl-rewriting

How to rewrite sub domain urls on main domain?


I need a help with configuring my htaccess. I need to re-write all sub domain urls to main domain.

This is my htaccess:

 RewriteEngine On

 Options +SymLinksIfOwnerMatch

# http => https
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# add www to main domain
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L,NE]

# language subdomains handler
RewriteCond %{QUERY_STRING} !(?:^|&)lang= [NC]
RewriteCond %{HTTP_HOST} ^([a-z]{2})\.
RewriteRule ^ %{REQUEST_URI}?lang=%1 [QSA,L]

I have other re-writed urls like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule ^about/$ /about.php [NC] 

This page works fine on main domain. https://www.example.com/about/

But in sub domain I get 404 error. https://en.example.com/about/

Can anyone guide me how to fix it ?

PS: It is another question related to : How to configure multiple languages via htaccess and sub domains as a GET method?

Thankyou


Solution

  • You can have your full .htaccess like this:

    Options +SymLinksIfOwnerMatch
    RewriteEngine On
    
    # http => https
    RewriteCond %{SERVER_PORT} 80 
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
    
    # add www to main domain
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
    RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
    RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L,NE]
    
    # language subdomains handler
    RewriteCond %{QUERY_STRING} !(?:^|&)lang= [NC]
    RewriteCond %{HTTP_HOST} ^([a-z]{2})\.
    RewriteRule ^ %{REQUEST_URI}?lang=%1 [QSA]
    
    # php extension handler e.g. /about/ => /about.php
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]