Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

apache - How to redirect non-www to www URL's using htaccess?

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/

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/

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...