如何使用 .htaccess 规则将所有 HTTP 请求重定向到 HTTPS?

发布于 2024-09-30 20:09:18 字数 234 浏览 9 评论 0 原文

我正在尝试将我的网站(例如 http://www.example.com)上的所有不安全 HTTP 请求重定向到 HTTPS (<代码>https://www.example.com)。如何在 .htaccess 文件中执行此操作?

顺便说一句,我正在使用 PHP

I'm trying to redirect all insecure HTTP requests on my site (e.g. http://www.example.com) to HTTPS (https://www.example.com). How can I do this in .htaccess file?

By the way, I'm using PHP.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

南…巷孤猫 2024-10-07 20:09:19

我建议使用 301 重定向:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

I'd recommend with 301 redirect:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
海的爱人是光 2024-10-07 20:09:19

正如我在 这个问题,我建议您避免盲目地将所有 HTTP 请求重定向到其 HTTPS 等效项,因为这可能会给您带来安全性的错误印象。相反,您可能应该将 HTTP 站点的“根”重定向到 HTTPS 站点的根,并从那里仅链接到 HTTPS。

问题是,如果 HTTPS 站点上的某些链接或表单使客户端向 HTTP 站点发送请求,则在重定向之前其内容将是可见的。

例如,如果通过 HTTPS 提供的某个页面的表单显示

并发送一些不应发送的数据以明文发送,浏览器将首先将完整请求(包括实体,如果是 POST)发送到 HTTP 站点。重定向将立即发送到浏览器,并且由于大量用户禁用或忽略警告,因此很可能会被忽略。

当然,一旦您在与您的 HTTPS 站点相同的 IP 地址上的 HTTP 端口上侦听某些内容,提供应该指向 HTTPS 站点但最终指向 HTTP 站点的链接的错误可能会导致问题。但是,我认为将这两个站点保留为“镜像”只会增加犯错误的机会,因为您可能倾向于假设它会通过将用户重定向到 HTTPS 来自动更正,但通常为时已晚。 (

As I was saying in this question, I'd suggest you avoid redirecting all HTTP requests to their HTTPS equivalent blindly, as it may cause you a false impression of security. Instead, you should probably redirect the "root" of your HTTP site to the root of your HTTPS site and link from there, only to HTTPS.

The problem is that if some link or form on the HTTPS site makes the client send a request to the HTTP site, its content will be visible, before the redirection.

For example, if one of your pages served over HTTPS has a form that says <form action="http://example.com/doSomething"> and sends some data that shouldn't be sent in clear, the browser will first send the full request (including entity, if it's a POST) to the HTTP site first. The redirection will be sent immediately to the browser and, since a large number of users disable or ignore the warnings, it's likely to be ignored.

Of course, the mistake of providing the links that should be to the HTTPS site but that end up being for the HTTP site may cause problems as soon as you get something listening on the HTTP port on the same IP address as your HTTPS site. However, I think keeping the two sites as a "mirror" only increases the chances of making mistakes, as you may tend to make the assumption that it will auto-correct itself by redirecting the user to HTTPS, whereas it's often too late. (There were similar discussions in this question.)

扛起拖把扫天下 2024-10-07 20:09:19

HTML 重定向方法。

它有效,但不是最好的。

<meta http-equiv="Refresh" content="0;URL=https://www.example.com" />

PHP 方法

<?php
function redirectTohttps() {
    if ($_SERVER['HTTPS']!="on") {
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        header("Location:$redirect"); 
    } 
}
?>

.htaccess 方法

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

复制自:
www.letuslook.org

HTML redirect approach.

It works, but it's not the best.

<meta http-equiv="Refresh" content="0;URL=https://www.example.com" />

PHP approach

<?php
function redirectTohttps() {
    if ($_SERVER['HTTPS']!="on") {
        $redirect= "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        header("Location:$redirect"); 
    } 
}
?>

.htaccess approach

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

copied from:
www.letuslook.org

凉墨 2024-10-07 20:09:19

我发现域上 https 和 www 的最佳方式是

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

I found out that the best way for https and www on domain is

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
如此安好 2024-10-07 20:09:19

最佳解决方案取决于您的要求。这是之前发布的答案的摘要,并添加了一些上下文。

如果您使用 Apache Web 服务器并且可以更改其配置,请遵循 Apache文档

<VirtualHost *:80>
    ServerName www.example.com
    Redirect "/" "https://www.example.com/"
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

但您还询问是否可以在 .htaccess 文件中执行此操作。在这种情况下,您可以使用 Apache 的 RewriteEngine

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

如果一切正常并且如果您希望浏览器记住此重定向,则可以通过将最后一行更改为:来将其声明为永久重定向,

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

但如果您可能对此重定向改变主意,请小心。浏览器会记住它很长一段时间并且不会检查它是否发生变化。

您可能不需要第一行 RewriteEngine On,具体取决于网络服务器配置。

如果您正在寻找 PHP 解决方案,请查看 $_SERVER 数组标头函数

if (!$_SERVER['HTTPS']) {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); 
} 

The best solution depends on your requirements. This is a summary of previously posted answers with some context added.

If you work with the Apache web server and can change its configuration, follow the Apache documentation:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect "/" "https://www.example.com/"
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

But you also asked if you can do it in a .htaccess file. In that case you can use Apache's RewriteEngine:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

If everything is working fine and you want browsers to remember this redirect, you can declare it as permanent by changing the last line to:

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

But be careful if you may change your mind on this redirect. Browsers remember it for a very long time and won't check if it changed.

You may not need the first line RewriteEngine On depending on the webserver configuration.

If you look for a PHP solution, look at the $_SERVER array and the header function:

if (!$_SERVER['HTTPS']) {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); 
} 
我偏爱纯白色 2024-10-07 20:09:19

我喜欢这种从 http 重定向到 https 的方法。因为我不需要为每个站点进行编辑。

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

I like this method of redirecting from http to https. Because I don't need to edit it for each site.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
有木有妳兜一样 2024-10-07 20:09:19

在 .htaccess 文件中使用以下代码会自动将访问者重定向到站点的 HTTPS 版本:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

如果您有现有的 .htaccess 文件:

请勿重复 RewriteEngine On。

确保以 RewriteCond 和 RewriteRule 开头的行紧跟在已存在的 RewriteEngine On 后面。

Using the following code in your .htaccess file automatically redirects visitors to the HTTPS version of your site:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If you have an existing .htaccess file:

Do not duplicate RewriteEngine On.

Make sure the lines beginning RewriteCond and RewriteRule immediately follow the already-existing RewriteEngine On.

农村范ル 2024-10-07 20:09:19

如果您无法直接访问站点的 apache 配置,而许多托管平台仍然受到这种方式的限制,那么我实际上会建议采用两步方法。 Apache 自己记录的原因是,对于 HTTP 到 HTTPS,您应该首先使用其配置选项而不是 mod_rewrite。

首先,如上所述,您将设置您的 .htaccess mod_rewrite 规则:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

然后,在您的 PHP 文件中(您需要在适合您情况的地方执行此操作,某些网站将通过以下方式汇集所有请求)一个 PHP 文件,其他文件根据需要和发出的请求提供不同的页面):

<?php if ($_SERVER['HTTPS'] != 'on') { exit(1); } ?>

上述内容需要在任何可能在不安全的环境中暴露安全数据的代码之前运行。因此,您的站点通过 HTACCESS 和 mod_rewrite 使用自动重定向,而您的脚本确保在不通过 HTTPS 访问时不提供输出。

我想大多数人不这么认为,因此 Apache 建议您尽可能不要使用这种方法。但是,只需在开发端进行额外检查即可确保用户数据的安全。希望这对由于我们的托管服务端的限制而可能不得不考虑使用非推荐方法的其他人有所帮助。

If you are in a situation where your cannot access the apache config directly for your site, which many hosted platforms are still restricted in this fashion, then I would actually recommend a two-step approach. The reason why Apache themselves document that you should use their configuration options first and foremost over the mod_rewrite for HTTP to HTTPS.

First, as mentioned above, you would setup your .htaccess mod_rewrite rule(s):

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Then, in your PHP file(s) (you need to do this where ever it would be appropriate for your situation, some sites will funnel all requests through a single PHP file, others serve various pages depending on their needs and the request being made):

<?php if ($_SERVER['HTTPS'] != 'on') { exit(1); } ?>

The above needs to run BEFORE any code that could potentially expose secure data in an unsecured environment. Thus your site uses automatic redirection via HTACCESS and mod_rewrite, while your script(s) ensure no output is provided when not accessed through HTTPS.

I guess most people don't think like this, and thus Apache recommends that you don't use this method where possible. However, it just takes an extra check on the development end to ensure your user's data is secure. Hopefully this helps someone else who might have to look into using non-recommended methods due to restrictions on our hosting services end.

墨落成白 2024-10-07 20:09:19

执行上面解释的所有重定向操作。只需将“HTTP 严格传输安全”添加到您的标头即可。这将避免中间人攻击。

编辑您的 apache 配置文件(例如 /etc/apache2/sites-enabled/website.conf 和 /etc/apache2/httpd.conf)并将以下内容添加到您的 VirtualHost:

# Optionally load the headers module:
LoadModule headers_module modules/mod_headers.so

<VirtualHost 67.89.123.45:443>
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>

https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security

Do everything that is explained above for redirection. Just add "HTTP Strict Transport Security" to your header. This will avoid man in the middle attack.

Edit your apache configuration file (/etc/apache2/sites-enabled/website.conf and /etc/apache2/httpd.conf for example) and add the following to your VirtualHost:

# Optionally load the headers module:
LoadModule headers_module modules/mod_headers.so

<VirtualHost 67.89.123.45:443>
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>

https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security

隔纱相望 2024-10-07 20:09:19

根据 GoDaddy.com,这是使用 .htaccess 将 HTTP 重定向到 HTTPS 的正确方法。第一行代码是不言自明的。第二行代码检查 HTTPS 是否关闭,如果是,则通过运行第三行代码将 HTTP 重定向到 HTTPS,否则忽略第三行代码。

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

https://www.godaddy.com/help/redirect- http-to-https-automatically-8828

This is the proper method of redirecting HTTP to HTTPS using .htaccess according to GoDaddy.com. The first line of code is self-explanatory. The second line of code checks to see if HTTPS is off, and if so it redirects HTTP to HTTPS by running the third line of code, otherwise the third line of code is ignored.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

https://www.godaddy.com/help/redirect-http-to-https-automatically-8828

意犹 2024-10-07 20:09:19

将以下代码添加到 .htaccess 文件中:

Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]

其中 [您的域名] 是您网站的域名。

您还可以通过将上面代码的最后一行替换为以下内容,将特定文件夹重定向到您的域名:

RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]

Add the following code to the .htaccess file:

Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]

Where [your domain name] is your website's domain name.

You can also redirect specific folders off of your domain name by replacing the last line of the code above with:

RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]
半城柳色半声笛 2024-10-07 20:09:19

要将所有 http 请求重定向到 https ,您可以使用:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

如果未启用 mod-rewrite 并且您使用的是 apache 2.4,您还可以使用 Redirect 内的 if 指令将 http 请求重定向到 https

阿帕奇2.4。

<if "%{HTTPS} !~ /on/">
Redirect / https://www.example.com/
</if>

To redirect all http requests to https , you can use :

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]

If mod-rewrite isn't enabled and you are on apache 2.4, you can also use a Redirect inside if directive to redirect http requests to https .

Apache 2.4.

<if "%{HTTPS} !~ /on/">
Redirect / https://www.example.com/
</if>
悲念泪 2024-10-07 20:09:19

除非您需要 mod_rewrite 来做其他事情,否则使用 Apache core IF 指令会更干净。更快:

<If "%{HTTPS} == 'off'">
Redirect permanent / https://yoursite.com/
</If>

您可以向 IF 指令添加更多条件,例如确保没有 www 前缀的单个规范域:

<If "req('Host') != 'myonetruesite.com' || %{HTTPS} == 'off'">
Redirect permanent / https://myonetruesite.com/
</If>

对所有内容使用 mod_rewrite 都有很多熟悉惯性,但看看这是否适合您。

更多信息: https://httpd.apache.org/docs/2.4 /mod/core.html#if

要查看其实际效果(尝试不使用 www. 或 https://,或者使用 .net 而不是 .com): https://nohodental.com/(我正在开发的网站)。

Unless you need mod_rewrite for other things, using Apache core IF directive is cleaner & faster:

<If "%{HTTPS} == 'off'">
Redirect permanent / https://yoursite.com/
</If>

You can add more conditions to the IF directive, such as ensure a single canonical domain without the www prefix:

<If "req('Host') != 'myonetruesite.com' || %{HTTPS} == 'off'">
Redirect permanent / https://myonetruesite.com/
</If>

There's a lot of familiarity inertia in using mod_rewrite for everything, but see if this works for you.

More info: https://httpd.apache.org/docs/2.4/mod/core.html#if

To see it in action (try without www. or https://, or with .net instead of .com): https://nohodental.com/ (a site I'm working on).

沒落の蓅哖 2024-10-07 20:09:19
 Redirect 301 / https://example.com/

(当上述答案都不起作用时,对我有用)

奖金:(

ServerAlias www.example.com example.com

修复了 https://www.example.com 未找到)

 Redirect 301 / https://example.com/

(worked for me when none of the above answers worked)

Bonus:

ServerAlias www.example.com example.com

(fixed https://www.example.com not found)

初吻给了烟 2024-10-07 20:09:19

我尝试了在互联网上可以找到的所有 .htaccess 配置,但没有一个起作用。
然后,我意识到 Apache 不鼓励使用 mod_rewrite< /代码>。

我的解决方案是编辑以下文件夹下的 apache 配置文件:
/etc/apache2/sites-enabled

您将拥有一个名为 000-default.conf 的强制文件和一个名为 000-default-le-ssl 的 ssl 配置文件.conf(如果您已安装来自 LetsEncrypt/certBot 的 ssl 证书)。但是,这些文件的名称可能有所不同,具体取决于您在设置站点时提供的文件名。

000-default.conf 中,我在 中将以下内容编辑为:

<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
</VirtualHost>

000-default-le-ssl.conf 中code>,我在 中编辑了以下内容:

<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
</VirtualHost>

不需要其他重定向。

保存文件,然后使用 sudo service apache2 restart 重新启动 apache 服务器

I tried all .htaccess configurations I could find on the internet but none worked.
Then, I realized Apache discourages using mod_rewrite.

My solution was to edit apache configuration files under the following folder:
/etc/apache2/sites-enabled

You will have one mandatory file named 000-default.conf and an ssl configuration file named 000-default-le-ssl.conf (if you have installed ssl certificate from letsencrypt/certbot). However, these files can be named differently depending on the file names you provided when setting up the site.

In 000-default.conf, I edited the following inside <VirtualHost *:80> as:

<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
</VirtualHost>

In 000-default-le-ssl.conf, I edited the following inside <VirtualHost *:80> as:

<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
</VirtualHost>

No other redirection is needed.

Save the file then restart the apache server using sudo service apache2 restart

浅听莫相离 2024-10-07 20:09:19

以上内容仅适用于 Apache 服务器。如果在 tomcat 上运行 PHP 会怎样?

所以你可以使用PHP代码,无论是Apache/tomcat/Nginx等...

if (!((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))){
    $redirect = 'https://' . str_replace($_SERVER['SERVER_PORT'], 8443, $_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

The above things are for the Apache server only. What if running PHP at tomcat?

So you can use PHP code, whether it is Apache/tomcat/Nginx etc...

if (!((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))){
    $redirect = 'https://' . str_replace($_SERVER['SERVER_PORT'], 8443, $_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}
め七分饶幸 2024-10-07 20:09:19

实际上,我试图让它在没有负载均衡器的 EC2 实例上运行,因为这需要花钱。我到处都读到 .htaccess 不是“正确”的方法。显然,它会起作用,但我试图按章办事。我按照所有示例来更新 httpd.conf 文件并添加了很多不必要的内容。事实证明,您真正需要的唯一一行是:

Redirect permanent / https://www.yourdomain.com

我的问题是,最初我已将其添加到 httpd.conf 内的 VirtualHost 标记中,这是很多帖子告诉您要做的事情,但它不起作用。事实证明,/etc/httpd/conf.d 中存储了一个名为 yourdomain.conf 的单独的 conf 文件,该文件已经具有 VirtualHost 标记,并且覆盖了我的 httpd.conf 设置。我刚刚在其中添加了上面的行,瞧,它立即重定向到 https。端口 443 不需要单独的 VirtualHost。

它现在正在工作,VirtualHost 标记如下所示:

<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/html
    ServerAlias www.yourdomain.com
    ErrorLog /var/www/error.log
    CustomLog /var/www/requests.log combined
    Redirect permanent / https://www.yourdomain.com
</VirtualHost>

注意:我已经使用来自 certbot 的免费证书进行了 TLS 设置(喜欢那些家伙),并且只是尝试重定向常规 http 调用到工作 https 站点。

I was actually trying to get this to work on an EC2 instance without a load balancer since that costs money. I've read everywhere that .htaccess isn't the "right" way to do it. Obviously, it will work, but I was trying to keep things by the book. I was following all of the examples to update the httpd.conf file and adding a lot of unnecessary stuff. It turns out the only line you really need is this:

Redirect permanent / https://www.yourdomain.com

My problem was that originally I had added this in a VirtualHost tag inside of httpd.conf, which is what a lot of posts tell you to do, but it wasn't working. It turns out there was a separate conf file stored in /etc/httpd/conf.d called yourdomain.conf which already had the VirtualHost tag and was overriding my httpd.conf settings. I just added the above line inside of it and voila, it instantly redirected to https. There is no need for the separate VirtualHost for port 443.

It's working now and the VirtualHost tag looks like this:

<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/html
    ServerAlias www.yourdomain.com
    ErrorLog /var/www/error.log
    CustomLog /var/www/requests.log combined
    Redirect permanent / https://www.yourdomain.com
</VirtualHost>

Note: I already had TLS setup with a FREE certificate from certbot (Love those guys) and was just trying to redirect regular http calls to the working https site.

梦途 2024-10-07 20:09:19

在 http 到 https 重定向的情况下,如果您无权访问主服务器配置文件,并且有义务在 . htaccess 文件代替。

In the case of the http-to-https redirection, the use of RewriteRule would be appropriate if you don't have access to the main server configuration file, and are obliged to perform this task in a .htaccess file instead.

各自安好 2024-10-07 20:09:19

将此代码复制到您的 .htaccess 文件中
自动将 HTTP 重定向到 HTTPS

RewriteEngine 开启
RewriteCond %{HTTPS} 已关闭
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

take this code to you .htaccess file
Redirect HTTP to HTTPS automatically

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

短暂陪伴 2024-10-07 20:09:19

您不仅可以在 .htaccess 文件中执行此操作,而且您应该在这段时间内执行此操作。您还需要按照此处的步骤操作,在实施此重定向后将您的网站列入 HSTS 预加载列表,以便对您网站的不安全 http 版本的任何请求都不会通过用户代理。相反,用户代理会根据内置的仅 https 网站列表检查请求的 URI,如果请求的 URI 位于该列表中,则在将请求传输到服务器之前将协议从 http 更改为 https。因此,不安全的请求永远不会传播出去,也永远不会到达服务器。最终,当互联网切换为 https 时,将不再需要 HSTS 预加载列表。在那之前,每个网站都应该使用它。

为了执行重定向,我们需要启用重写引擎,然后将所有流量从 http 端口 80 重定向到 https。

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourwebsite.tld/$1 [L,R=301]

Not only can you do this in your .htaccess file, you should be doing this period. You will also want to follow the steps here to get your site listed on the HSTS preload list after you implement this redirect so that any requests to the insecure http version of your website never make it past the user agent. Instead, the user agent checks the requested URI against a baked in list of https only websites and, if the requested URI is on that list, changes the protocol from http to https before transmitting the request to the server. Therefore, the insecure request never makes it out into the wild and never hits the server. Eventually when the internet changes over to https only the HSTS preload list will not be needed. Until then, every site should be using it.

In order to perform the redirect, we need to enable the rewrite engine and then redirect all traffic from the http port 80 to https.

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourwebsite.tld/$1 [L,R=301]
榕城若虚 2024-10-07 20:09:19

经过多次尝试,考虑没有 www 和有 www 这有效

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

After lots of tries by considering without www and with www this works this

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
痴者 2024-10-07 20:09:19

如果您想从 tomcat 服务器执行此操作,请按照以下步骤

在独立的 Apache Tomcat (8.5.x) HTTP 服务器中,如何配置它,以便用户键入 www.domain.com,它们将自动转发到 https(www. domain.com)网站。

两步方法是在 WEB-INF/web.xml 结束标记之前包含以下内容

step 1: 
<security-constraint>
<web-resource-collection>
<web-resource-name>HTTPSOnly</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

并设置 [Tomcat_base]/conf/server.xml 连接器设置:

step 2:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="[keystorelocation]" type="RSA" />
</SSLHostConfig>
</Connector>

注意:如果您已经完成了 https 配置并尝试重定向,请执行以下操作:仅第 1 步。

If you want to do it from the tomcat server follow the below steps

In a standalone Apache Tomcat (8.5.x) HTTP Server, how can configure it so if a user types www.domain.com, they will be automatically forwarded to https(www.domain.com) site.

The 2 step method of including the following in your WEB-INF/web.xml before the closing tag

step 1: 
<security-constraint>
<web-resource-collection>
<web-resource-name>HTTPSOnly</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

and setting the [Tomcat_base]/conf/server.xml connector settings:

step 2:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="[keystorelocation]" type="RSA" />
</SSLHostConfig>
</Connector>

Note: If you already did the https configuration and trying to redirect do step 1 only.

家住魔仙堡 2024-10-07 20:09:19

通过 .htaccess 这会有所帮助。

RewriteEngine On


RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

另外,请参阅此了解更多详细信息。 如何将 Http 重定向到 Https?

Through .htaccess This will help.

RewriteEngine On


RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Also, Refer this for More Detail. How To Redirect Http To Https?

暗地喜欢 2024-10-07 20:09:19

这会将所有 URL 重定向到 https 和 www

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

This redirects all the URLs to https and www

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
水中月 2024-10-07 20:09:19

如果您使用 Apache,mod_rewrite 是最简单的解决方案,并且在线有大量文档说明如何做到这一点。例如: http://www.askapache.com/htaccess/http- https-rewriterule-redirect.html

If you are using Apache, mod_rewrite is the easiest solution, and has a lot of documentation online how to do that. For example: http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html

ゞ花落谁相伴 2024-10-07 20:09:19

如果您使用的 Amazon Web Services Elastic Load Balancer 接受 https 流量并通过 http 将其路由到您的服务器,则此处描述了将所有 http 流量重定向到 https 的正确方法:https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https- elb

使用 X-Forwarded-Proto 标头(包含 http 或 https),该标头始终包含在来自负载均衡器的 http 请求中,如下所述:https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html

在 httpd.conf 文件中:

<VirtualHost *:80>

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

</VirtualHost>

或者在您的根 .htaccess 文件中:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

额外好处:它不会尝试在本地开发计算机上重定向 http 流量。

If you're using an Amazon Web Services Elastic Load Balancer which accepts https traffic and routes it to your server(s) with http, the correct way to redirect all http traffic to https is described here: https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https-elb

Use the X-Forwarded-Proto header (contains http or https) which is always included in http requests from the load balancer, as described here: https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html

In the httpd.conf file:

<VirtualHost *:80>

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

</VirtualHost>

Or in your root .htaccess file:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

Bonus: it will not try to redirect http traffic on your local development machine.

梦回梦里 2024-10-07 20:09:19

它对我有用:

<IfModule mod_rewrite.c>
 RewriteEngine On
  RewriteCond %{HTTPS} !on
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

例如 http:// /server/foo?email=someone%40example.com 正常重定向,没有任何问题。
文件 .htaccess 位于网站根文件夹(例如名为 public_html)。
可以使用
RewriteCond %{SERVER_PORT} !^443$ 改为 RewriteCond %{HTTPS} !on

It works for me:

<IfModule mod_rewrite.c>
 RewriteEngine On
  RewriteCond %{HTTPS} !on
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

and for example, http://server/foo?email=someone%40example.com redirects normally without any issues.
The file .htaccess located in the website root folder (for example named public_html).
It is possible to use
RewriteCond %{SERVER_PORT} !^443$ instead RewriteCond %{HTTPS} !on

装纯掩盖桑 2024-10-07 20:09:18

Apache 文档 建议不要使用重写:

要将 http URL 重定向到 https,请执行以下操作:

<虚拟主机 *:80>
    服务器名称 www.example.com
    重定向/https://www.example.com/


<虚拟主机 *:443>
    服务器名称 www.example.com
    # ... SSL 配置位于此处

此代码段应进入主服务器配置文件,而不是进入 .htaccess< /code> 如问题中所问。

这篇文章可能是在问题被提出并回答之后才出现的,但似乎是当前的发展方向。

The Apache docs recommend against using a rewrite:

To redirect http URLs to https, do the following:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost>

This snippet should go into main server configuration file, not into .htaccess as asked in the question.

This article might have come up only after the question was asked and answered, but seems to be the current way to go.

生死何惧 2024-10-07 20:09:18

在您的 .htaccess 文件中添加以下内容

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Add the following inside your .htaccess file

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文