简体   繁体   English

htaccess使用子域重定向

[英]htaccess redirect with sub-domain

I have a domain example.com and in .htaccess, I am forwarding non-www to www address using below code. 我有一个域example.com,在.htaccess中,我正在使用以下代码将非www转发到www地址。

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

Now I created a subdomain test.example.com and because of above rule, its going to http://www.test.example.com , so I thought to write it's own htaccess file to redirect www to non-www. 现在,我创建了一个子域test.example.com,由于上述规则,它进入了http://www.test.example.com ,因此我想编写它自己的htaccess文件将www重定向到非www。 So in the subdomain root, I have .htaccess file with below rule. 因此,在子域根目录中,我具有以下规则的.htaccess文件。

RewriteEngine On
RewriteCond %{HTTP_HOST} !^test\.example\.com$ [NC]
RewriteRule ^(.*)$ http://test.example.com/$1 [R=301,L]

It's not working and going in a redirect loop , how do I fix it? 它无法正常工作,并且进入重定向循环 ,该如何解决?

Take out the ! 拿出! and the escapes 和逃生

RewriteEngine On
RewriteCond %{HTTP_HOST} ^test.example.com$
RewriteRule ^(.*)$ http://test.example.com/$1 [R=301,L]

You don't need 2 rules. 您不需要2条规则。 Just keep this rule in main .htaccess for your main domain: 只需将此规则保留在您的主域的main .htaccess中:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

Now RewriteCond %{HTTP_HOST} ^example\\.com$ condition will only impact main domain leaving your sub domain untouched. 现在, RewriteCond %{HTTP_HOST} ^example\\.com$条件将仅影响主域,而使您的子域保持不变。

I found a very easy solution for this problem. 我找到了解决这个问题的简单方法。

My main site document root was /home/example/public_html and subdomain document root was /home/example/public_html/test . 我的主站点文档根是/home/example/public_html ,子域文档根是/home/example/public_html/test

I just changed the document root of subdomain to /home/example/test and it worked. 我只是将子域的文档根目录更改为/home/example/test并且可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM