Rewrite URL using Apache for redirecting root domain

亡梦爱人 提交于 2019-12-22 12:19:36

问题


I have this scenario where I would like to redirect my domains using the following scenario. Can you please advice if this can be achieved using RewriteRule in Apache?

I would like to redirect any calls made using http://www.domainname.com/url to redirect to http://domainname.com/url.

I was able to achieve the above using the following rewrite rule

# BEGIN WithoutWWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$ [NC]
RewriteRule ^(.*)$ http://domainname.com/$1 [R=301,L]
# END WithoutWWW

If anyone tries to visit just http://www.domainname.com or http://domainname.com, I would like them to redirect to http://dname.com

How can I achieve this rule using RewriteRule in Apache? I'm also using PHP, so a solution using PHP would be valid too.


回答1:


Here is your combined .htaccess with your existing and new code:

RewriteEngine on

# redirect domainname.com/ or www.domainname.com/ to dname.com/
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.com$ [NC]
RewriteRule ^$ http://dname.com [R=301,L]

# append www to domainname.com    
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$ [NC]
RewriteRule ^ http://domainname.com%{REQUEST_URI} [R=301,L]



回答2:


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



回答3:


That example looks like mod_rewrite. With mod_rewrite you could do:

# BEGIN WithoutWWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.com$ [NC]
RewriteRule ^(.*)$ http://dname.com/$1 [R=301,L]
# END WithoutWWW

You may want to look at http://www.workingwith.me.uk/articles/scripting/mod_rewrite

Based on your comment you want to redirect the root differently so we could do:

RewriteEngine on
#www.domainname.com & domainname.com -> dname.com
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.com$ [NC]
RewriteRule ^$ http://dname.com/ [R=301,L]

#www.domainname.com/[url] -> domainname.com/[url]
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$ [NC]
RewriteRule ^(.*)$ http://domainname.com/$1 [R=301,L]


来源:https://stackoverflow.com/questions/10017224/rewrite-url-using-apache-for-redirecting-root-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!