使用 mod_rewrite 的 Apache ssl 重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1278262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 18:03:52  来源:igfitidea点击:

Apache ssl redirect using mod_rewrite

apachemod-rewrite

提问by

I want to do this: if they do https://example.comI want to redirect them to https://www.example.com(add the www.). I have tried oodles of things to no avail.

我想这样做:如果他们这样做,https://example.com我想将他们重定向到https://www.example.com(添加www.)。我尝试了很多事情都无济于事。

Redirect https://example.com/<anything> to https://www.example.com/<anything>
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} =443
RewriteRule ^(.*)$ https://www.example.com/ [R=301,L] 

This code is in httpd.conf but has been tried in .htaccess and ssl.conf.

此代码在 httpd.conf 中,但已在 .htaccess 和 ssl.conf 中尝试过。

Can anyone help?

任何人都可以帮忙吗?

回答by Residuum

Have you turned on Rewriting via RewriteEngine Onor is mod_rewrite installed? Otherwise, your code should work.

您是否打开了重写通过RewriteEngine On或是否安装了 mod_rewrite?否则,您的代码应该可以工作。

回答by Gumbo

The Redirectdirectivedoes only work on the URL path. But it's possible with mod_rewrite. This rule will work in any configuration file:

Redirect指令仅适用于 URL 路径。但是使用 mod_rewrite 是可能的。此规则适用于任何配置文件:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteCond %{SERVER_PORT} =443
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

And don't forget the obligatory RewriteEngine onlike (Residuum already said)(1278432#1278432).

并且不要忘记RewriteEngine on像 (Residuum 已经说过)(1278432#1278432) 这样的强制性要求。

回答by Adrián Navarro

Use this:

用这个:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.example.com/ [R,L]

Of course, don't forget to replace "www.example.com" with your own domain.

当然,不要忘记将“www.example.com”替换为您自己的域。