重定向www。到非www并使用.htaccess

时间:2016-09-04 12:46:25

标签: .htaccess redirect mod-rewrite

百万次问问题,但在阅读了这里的许多答案后,我仍然无法弄清楚这一点。我需要重定向所有请求,如下所示:

  1. http://domain.tld> https://domain.tld
  2. http://www.domain.tld> https://domain.tld
  3. https://www.domain.tld> https://domain.tld
  4. http://sub.domain.tld> https://sub.domain.tld(当.htaccess置于子域文件夹中时)
  5. 到现在为止,我正在使用html5boilerplate中的代码,将www解析为非www

    <IfModule mod_rewrite.c>
      RewriteCond %{HTTPS} !=on
      RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
      RewriteRule ^(.*)$ http://%1/ [R=301,L]
    </IfModule>
    

    他们还有一个http到https重定向的代码,但在添加这段代码后(在www重定向上面),页面正在加载,超时后显示错误/重定向太多

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

    我也尝试过像this SO answer这样的例子,但网站仍无效。目前唯一的解决方案是使用第一段代码并将http替换为https,但这并不能解决最重要的重定向问题(1)

    当前的完整.htaccess内容:

    <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteBase /
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)\/$ /$1 [R=301,L]
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule /?([A-Za-z0-9_-]+)/?$ index.php?id=$1 [QSA,L]
    
        #RewriteCond %{HTTPS} off [OR] #by uncommenting this, site stops working
        RewriteCond %{HTTP_HOST} ^www
        RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
        RewriteRule ^ https://%1%{REQUEST_URI} [R,L]
    </IfModule>
    

2 个答案:

答案 0 :(得分:1)

要在单个http请求中重定向到https和非www,您可以使用

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]

在测试此规则之前清除浏览器的缓存。

答案 1 :(得分:1)

有时,根据某些服务器配置,似乎public class AnalyticsFragment extends Fragment { @Override public void onResume() { super.onResume(); // Listen to custom intent with data IntentFilter filter = new IntentFilter("com.keyone.contactpackapp.ANALYTICS_DATA"); m_receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Get data from intent and pass it to the right fragment String szJson = intent.getStringExtra("response"); //m_response = new Gson().fromJson(szJson, GetReportsResponse.class); Type listType = new TypeToken<GetReportsResponse>(){}.getType(); m_response = new Gson().fromJson(szJson, listType); Fragment fragment = m_activity.currentFragment(); fragment.updateData(); } }; if (m_activity != null) m_activity.registerReceiver(m_receiver, filter); } } 变量始终设置为HTTPS。这可以解释循环,我已经在SO上看到了类似的情况。

一个简单的解决方法是测试off(如果您使用默认的80和443),或者您也可以测试SERVER_PORT

示例(1)测试它是否 HTTP:X-Forwarded-Proto

https

示例(2)测试它是否 RewriteCond %{HTTP:X-Forwarded-Proto} !https

https