将www重定向到非www,同时保持协议HTTP或HTTPS [英] Redirecting www to non-www while maintaining the protocol HTTP or HTTPS

查看:79
本文介绍了将www重定向到非www,同时保持协议HTTP或HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将HTTP和HTTPS请求的www重定向到非www.我的根.htaccess如下所示:

I'm attempting to redirect www to non-www for both HTTP and HTTPS requests. My root .htaccess looks like this:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^(.*)$ http://example.com/$1 [R=301]

RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} ^443
RewriteRule ^(.*)$ https://example.com/$1 [R=301]

这不能完全按预期工作.会发生什么:

This isn't fully working as expected. What happens:

访问http://www.example.com将导致重定向到http://example.com.这表明我的第一个规则和条件正在运行,mod_rewite模块是hunky-dory并且.htaccess已启用.

Visiting http://www.example.com results in a redirect to http://example.com. This indicates my first rule and condition are working, the mod_rewite module is hunky-dory and .htaccess is enabled OK.

访问https://www.example.com不会导致重定向.我仍然在https://www.example.com

Visiting https://www.example.com doesn't result in a redirect. I remain on https://www.example.com

我的问题

为了使上述重写规则生效,我的服务器必须具有SSL证书吗?目前还不行,我想知道那是否是事情不正常的原因.

In order for the above rewrite rules to work, must my server have an SSL certificate? It currently doesn't and I'm wondering if that is the reason things aren't working.

推荐答案

第一个规则优先于https请求,因为它完全满足重写条件.第一条规则基本上告诉您匹配域,您就可以开始重写了.而是添加另一个条件,以告知其是否不是https请求

The first rule is taking precedence over https request because it simply met the rewrite condition. The first rule basically tells that match the domain and you can have your rewriterule to kick off. Instead add another condition which tells if its not https request

所以尝试一下:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} !^443
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} ^443
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

要使https协议正常运行,您需要ssl证书

You need ssl certificate for https protocol to work

我还添加了[L]标志,该标志指示不要处理进一步的规则

Also I've added [L] flag which tells to not process further rules

这篇关于将www重定向到非www,同时保持协议HTTP或HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆