如何使用 htaccess 将非 www 重定向到 www URL? [英] How to redirect non-www to www URL's using htaccess?
问题描述
我有一个网站,在我的网站根目录中显示 http://www.example.com/,我添加了 .htaccess 文件以将 http://example.com/ 的任何请求重定向到 http://www.example.com/
I have a website say http://www.example.com/ in the root of my website, I have added .htaccess file to redirect any request of http://example.com/ to http://www.example.com/
最近我创建了一个新的视频"部分,所以视频的 URL 是 http://www.example.com/videos/ .在这个视频文件夹中,我有另一个 htaccess 文件,它正在为视频条目执行重写.当我尝试访问 http://example.com/videos/ 时,它不会将我重定向到
Recently I have created a new section "Videos" so the URL for videos is http://www.example.com/videos/ . In this video folder I have another htaccess file which is performing rewriting for video entries. When I am trying to access http://example.com/videos/ then its not redirecting me to http://www.example.com/videos/
我认为 .htacces 没有从父目录继承以前的规则.谁能告诉我可以在/videos/文件夹的 .htaccess 文件中添加什么规则,以便对 的任何请求http://example.com/videos/ 将被重定向到 http://www.example.com/videos/ 网址.
I think .htacces is not inheriting the previous rules from the parent directory. Can anyone please tell me what can be the rule I can add in the .htaccess file of /videos/ folder so that any request for http://example.com/videos/ will be redirected to http://www.example.com/videos/ URL.
推荐答案
这是一个更通用的解决方案,因为它可以与任何域名一起使用,而无需在每个 .htaccess 中指定特定的域名:
This is a more generic solution, because it can be used with any domain name without having to specify the specific domain name in each .htaccess:
# Redirect non-www to www:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
相反的情况也是可能的(www 到非 www):
The contrary is also possible (www to non-www):
# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
这篇关于如何使用 htaccess 将非 www 重定向到 www URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!