如何使用htaccess正确重定向?

时间:2015-04-03 07:48:38

标签: apache .htaccess mod-rewrite redirect

我试图在Apache中使用重写规则重定向 - .htaccess。我有一套规则可以很好地重定向所有http://到https://。

因此,如果用户尝试http://www.example-old.comhttp://example-old.comhttp://www.example-new.comhttp://example-new.com,则会将所有这些内容重定向到https://example-new.com

现在我想在服务器上再添加一个地址,我不希望将其重定向到https://example-new.com

所以我希望它从下面的代码中排除。如果有人尝试http://newest-example.com,则应该正确地重定向到它。

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [OR,NC]
RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC]
RewriteRule ^ https://example-new.com%{REQUEST_URI} [L,R=301]

除了上面的代码,我尝试的是:

RewriteCond %{HTTP_HOST} ^newest-example\.com$ [NC]
RewriteRule ^ http://newest-example.com [R=301,S=1]

此代码高于我提交的第一个块。就像你可以看到我试图跳过S = 1的原始RewriteRule,如果URL是http://newest-example.com但是这给了我这样的信息:

Moved Permanently

The document has moved here.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

没有经验,我不知道我在这里失踪了什么。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以在第一条规则中添加排除规则:

RewriteCond %{HTTP_HOST} !^newest-example\.com$ [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [OR,NC]
RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC]
RewriteRule ^ https://example-new.com%{REQUEST_URI} [L,R=301]