http to https htaccess redirect loop error

2019-09-06 01:32发布

I have a site which I am trying to completely redirect from http to https.

I need to redirect any user that arrives at the site via http to the same page on https.

The site is hosted on a provider's shared hosting. Since the domain's SSL certificate was installed, a new IP address has been assigned to the domain.

I have been advised that the following code should be added to my .htaccess file. There are also some rules which handle SEO friendly URLS.

RewriteEngine On
RewriteBase /

# enforce https and www
RewriteCond %{SERVER_PORT} !=443 [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,NE,R=302]

# skip further rules for files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# internal rewrite rules
RewriteRule ^([\w-]+)/([\w-]+)/?$ page.php?venue=$1&artist=$2 [L,QSA]
RewriteRule ^([\w-]+)/?$ page.php?venue=$1 [L,QSA]

For some reason, the addition of this code to the .htaccess file, results in a redirection loop error. I have tried variants of the RewriteCond %{SERVER_PORT} !=443 line as advised on other Stack Overflow posts, but nothing seems to work.

Does anyone have a solution?

2条回答
放我归山
2楼-- · 2019-09-06 02:22

You can use this code in your root .htaccess:

RewriteEngine On
RewriteBase /

# enforce https and www
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,NE,R=302]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=302]

# skip further rules for files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# internal rewrite rules
RewriteRule ^([\w-]+)/([\w-]+)/?$ page.php?venue=$1&artist=$2 [L,QSA]
RewriteRule ^([\w-]+)/?$ page.php?venue=$1 [L,QSA]
查看更多
何必那么认真
3楼-- · 2019-09-06 02:27

I have been given this code from my service provider which seems to do the trick using php

<?php 
 if ($_SERVER['HTTP_X_FORWARDED_SSL'] == '1') {  } else {    $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];    header("Location: $redirect"); } ?>

I can add the following for permanent redirection

header("HTTP/1.1 301 Moved Permanently");
查看更多
登录 后发表回答