htaccess redirect only if domain matches

房东的猫 提交于 2020-07-04 12:17:39

问题


I have a problem where I need to redirect my domain before it hits php. By the time it hits the ability to execute a header, it is too late.

How can I do

if (domain == 'www.example.com')
redirect www.domain.com;

in my .htaccess?


回答1:


Using mod_rewrite

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



回答2:


As of Apache 2.4 you can use an <If> Directive to achieve what you suggested:

<If "req('Host') == 'www.example.com'">
  RedirectMatch (.*) http://www.example2.com$1
</If>

For a case-insensitive version that matches with or without the www you can do:

<If "req('Host') =~ /example.com/i">
  RedirectMatch (.*) http://www.example2.com$1
</If>

Sources:

  • Apache Blog: New in httpd 2.4: If, ElseIf, and Else
  • Apache 2.4 Documentation: If Directive


来源:https://stackoverflow.com/questions/10240065/htaccess-redirect-only-if-domain-matches

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