简体   繁体   中英

Redirect to subdomain route with www site using .htaccess

I have a website in which I have htaccess configured to redirect all the traffic to www website. So my website works like this: www.domain.com

Now I want to support subdomain feature for all the registered users for example username.domain.com but my current htaccess rules don't allow this when I hit such URL then it redirects subdomain URL to include www as well which I don't want. For example:

I hit username.domain.com and it becomes www.username.domain.com

Here is my current htaccess code:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How do I support both www for main site? So that when user hits subdomain URL then it should not add www in the URL.

I am not expert in URL rewriting, so apologies if I miss something obvious.

Thanks

On Apache 2.4+ you can use these rules in site root .htaccess:

RewriteEngine on

# if not main domain skip all rules
RewriteCond %{HTTP_HOST} !^(?:www\.)?domain\.com$ [NC]
RewriteRule ^ - [L]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

You can use:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

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