首页 文章

使用Apache将HTTP重定向到HTTPS

提问于
浏览
5

我有一个问题,使用mod_rewrite强制在Ubuntu Server 12.04上使用Apache 2.2.22将HTTP请求重定向到HTTPS .

我的/ etc / apache2 / sites-available / default文件如下:

<VirtualHost *:80>
        RewriteEngine On
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
    </VirtualHost>

HTTPS主机在default-ssl中定义在同一目录中 .

访问服务器的本地IP地址,重定向似乎工作正常 . 但是,通过FQDN访问它,它没有 . 使用FQDN,该站点在端口5443处可用,该端口在防火墙中映射到服务器上的443,因此可能与该问题有关 . 我不能直接使用端口443,因为它在另一台服务器上使用此IP地址 .

为进一步澄清,以下是有效链接:

https://website:5443
    https://192.168.200.80:443

重定向在这里工作:

http://192.168.200.80

但是下面给出了400 Bad Request,这是需要重定向的地方:

http://website:5443/

“您的浏览器发送了此服务器无法理解的请求 . 原因:您正在向支持SSL的服务器端口说明HTTP . 请使用HTTPS方案访问此URL . ”

4 回答

  • 0

    这完全有可能 . 以下内容将所有http重定向到https网址 .

    <VirtualHost *:80>
        ServerName   mydomainname.com
        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    </VirtualHost>
    

    确保加载重写模块mod_rewrite并启用它 .

  • 8

    这里的问题是初始HTTP请求:这不起作用,因为服务器不会理解它在端口443上接收请求(如响应代码所示) .

    如果没有给出端口,则协议 http 默认为端口80, https 为端口443 .

    这也是您的本地重定向工作的原因 . 我敢打赌,如果您通过 http://website/ (通过端口80的正确端口转发)访问该页面,它也将起作用 . 另请注意,您的 VirtualHost 仅为端口80定义,因此对于发送到 website:5443 (或 website:443 )的请求无效 .

    通常,您需要服务器在单个端口上接受HTTP和HTTPS请求 . 不确定任何流行的服务器实际上支持这样的东西,因为(我认为)它基本上违反了规范 .

  • 3

    如果您想将您的网站从http:// anything.example.com重定向到https://anything.example.com ...只需创建一个专用的托管.conf文件/etc/httpd/conf.d/dedicated . conf和其他conf文件为virtual.conf ... dedicated.conf的条目如下....

    这是专用服务器托管conf文件,用于将其重定向到https ...
    th

    <virtualhost *:80>
    servername host.example.com
    documentroot /var/www/html
    rewriteengine on
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
    sslcertificatefile /etc/pki/tls/certs/name.crt
    sslcertificatekeyfile /etc/pki/tls/private/name.key
    </virtualhost>
    <directory /var/www/html>
    allowoverride all
    require all granted
    </directory>
    

    Alternatively as mentioned in comment below, we can use redirect also:

    <virtualhost *:80>
    servername host.example.com
    documentroot /var/www/html
    RedirectMatch / https://host.example.com:ANY_PORT/ #if there is specific port
    sslcertificatefile /etc/pki/tls/certs/name.crt
    sslcertificatekeyfile /etc/pki/tls/private/name.key
    </virtualhost>
    <directory /var/www/html>
    allowoverride all
    require all granted
    </directory>
    
  • 1
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
    

相关问题