How to 301 redirect an entire domain while preserving the path

后端 未结 3 1651
臣服心动
臣服心动 2020-12-10 01:39

I am redirecting one domain to another, but I want to preserve the path in the redirect. So for example, I want to visit www.example.com/services/education/page.html

相关标签:
3条回答
  • 2020-12-10 01:58

    try adding the following to your .htaccess in the root of your example.com domain

    RewriteEngine On
    RewriteBase /
    
    #for all requests to www.example.com
    RewriteCond %{HTTP_HOST} ^www\.example\.com$
    #redirect them to new-example
    RewriteRule (.*) http://www.new-example.com/$1 [R=301,L]
    
    0 讨论(0)
  • 2020-12-10 01:59

    Your original command uses the mod_alias Apache module, and it would work, though you may want to update it to:

    Redirect 301 / http://www.new-example.com/
    

    Removing the exact domain of the current (old) domain means all domains that point to that folder will be sent to the new domain, making that one-line script more robust.

    The other answers use the mod_rewrite Apache module. If you have that also installed, that's fine to use, though it's 4+ lines of code compared to one. Additionally, mod_alias is part of the "base" package, so should be on all Apache servers, while mod_rewrite is an optional extension, so some might not have it.

    0 讨论(0)
  • 2020-12-10 02:11

    This should do it:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !new-example.com$ [NC]
    RewriteRule ^(.*)$ http://new-example.com/$1 [L,R=301]
    
    0 讨论(0)
提交回复
热议问题