将非 www 重定向到 .htaccess 中的 www [英] Redirect non-www to www in .htaccess

查看:34
本文介绍了将非 www 重定向到 .htaccess 中的 www的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 .htaccess 文件中有这个:

I have this in my .htaccess file:

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

但是每当我访问根目录上的文件时,例如 http://example.com/robots.txt 它将重定向到 http://www.example.comrobots.txt/.

but whenever I access a file on my root like http://example.com/robots.txt it will redirect to http://www.example.comrobots.txt/.

如何更正此问题以使其正确重定向到 http://www.example.com/robots.txt?

How can I correct this so that it will redirect correctly to http://www.example.com/robots.txt?

推荐答案

将您的配置更改为此(添加斜杠):

Change your configuration to this (add a slash):

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

或者下面列出的解决方案(由 @absiddiqueLive) 适用于任何域:

Or the solution outlined below (proposed by @absiddiqueLive) will work for any domain:

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

如果您需要支持 http 和 https 并保留协议选择,请尝试以下操作:

If you need to support http and https and preserve the protocol choice try the following:

RewriteRule ^login$ https://www.%{HTTP_HOST}/login [R=301,L]

login 替换为 checkout.php 或支持 HTTPS 所需的任何 URL.

Where you replace login with checkout.php or whatever URL you need to support HTTPS on.

不过,我认为这是一个坏主意.对于推理请阅读此答案.

I'd argue this is a bad idea though. For the reasoning please read this answer.

这篇关于将非 www 重定向到 .htaccess 中的 www的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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