使用.htaccess从http重定向到不带www的https


Redirect from http to https without www using .htaccess

我有一个基于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]

我如何可以重定向到https和没有www?

对于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]

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

<Directory />
  SSLRequireSSL
</Directory>

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

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

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

首先将所有带有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]

在sequance的.htaccess文件中逐一添加以上代码,将您的所有请求重定向到https,而不需要www

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