non www .htaccess redirect - ignore other subdomai

2020-05-27 13:41发布

I have a .htaccess redirect for "non www" like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

it is working. But, i have also some subdomains other than www. If I call for example http://shop.example.com it redirects me to: http://www.shop.example.com

I dont want to write the subdomains into the .htaccess file, it should work automatically, just ignore anything else than www and '' like this:

if subdomain =='' -> redirect to www.HTTP_HOST....
elseif subdomain !='' && subdomain !='www' -> do nothing.

thanks!

3条回答
叼着烟拽天下
2楼-- · 2020-05-27 14:11

try this:

Options +FollowSymlinks

RewriteEngine On

RewriteCond %{HTTP_HOST}//s%{HTTPS} ^www\.(.*)//((s)on|s.*)$ [NC]

RewriteRule ^ http%3://%1%{REQUEST_URI} [L,R=301]

Just tried it with internetagentur.drupal-webmaster.de (the subdomain) - the main is without www.

查看更多
Viruses.
3楼-- · 2020-05-27 14:11

Try this rule:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

And to also take HTTPS into account:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
查看更多
戒情不戒烟
4楼-- · 2020-05-27 14:15

If you want a php solution you could use something similar to this:

define('URL', 'yourdomain.com/');

// fix : impose www rule
if (strpos($_SERVER['SERVER_NAME'], 'www') === false ) {
    header('Location: http://www.'.URL.$_SERVER['REQUEST_URI']);
    die();
}

This would also redirect to the originally requested page.

查看更多
登录 后发表回答