【问题标题】:Redirect from http to https without www using .htaccess使用 .htaccess 从 http 重定向到 https 而不使用 www
【发布时间】:2015-05-03 01:31:15
【问题描述】:

我有基于 PHP 和 Apache 的应用程序。如果请求的链接不是目录或文件,则所有请求都转到 index.php 文件。我想将所有请求从 http 重定向到 https 并且没有 www。

我的有效链接:

  1. https://someaddress.org

从以下对我无效的链接开始(对不起,我的名声很小,我不能发布更多的 2 个链接):

  1. http://
  2. http://www.
  3. www.

我的 htaccess 是这样的

AddDefaultCharset UTF-8

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) index.php [L]

如何在没有 www 的情况下重定向到 https?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite


    【解决方案1】:

    http->httpwww 的删除有另一条规则:

    AddDefaultCharset UTF-8
    
    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteRule ^ https://someaddress.org%{REQUEST_URI} [L,NE,R=301]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    

    【讨论】:

    • 感谢您的回答,its work for redirect from http to https, but dont work for http:// www.someaddress.org .... and for www.someaddress.org im 正在尝试本地主机,现在我无法访问真实服务器
    • 这条规则会将http://www.someaddress.org重定向到https://someaddress.org
    • 我明天在真实服务器上再试一次,然后在这里发布结果。
    • 非常感谢!这个解决方案对我有用
    【解决方案2】:

    您可以使用 SSLRequireSSL 指令覆盖 http 到 https 部分。

    <Directory />
      SSLRequireSSL
    </Directory>
    

    如果问题是 htaccess 文件而不是重写规则,您可以停止使用 .htaccess 文件并将重写规则移至 apache 配置文件。

    如果您只是不想或可以使用重写规则,并且由于绝大多数 php 应用程序需要包含在每个脚本中的配置文件(例如配置变量或用户控件),您可以使用此文件来获取请求的资源并剥离 www。域名以它们开头的部分。

    如果包含文件可能是您需要的解决方案,我可以提供一个 php 代码示例。

    【讨论】:

    • 感谢您的回答,但我的问题现在已经解决了
    【解决方案3】:

    首先将所有带有 WWW 的请求重定向到没有 WWW 的 https

    # For http://www.yourdomain.com and https://www.yourdomain.com
    RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com [NC]
    RewriteRule ^(.*)$ https://yourdomain.com/$1 [L,R=301]
    

    现在将所有没有 WWW 的 http 请求重定向到没有 WWWW 的 https

    # For http://yourdomain.com
    RewriteCond %{HTTPS} =off
    RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
    RewriteRule ^(.*)$ https://yourdomain.com/$1 [L,R=301]
    

    在 .htacess 文件中依次添加上述代码,以将您的所有请求重定向到不带 www 的 https

    我使用“R=301”进行永久重定向

    【讨论】:

      猜你喜欢
      • 2016-01-20
      • 2015-02-16
      • 2016-08-31
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 2017-06-07
      相关资源
      最近更新 更多