Htaccess - Rewrite from http to https and www to n

2019-02-28 14:57发布

问题:

I am trying to rewrite form http to https and www to non-www urls.

Basically if someone goes to http://www.example.com they need to be redirected to https://example.com and all other instances of wrong urls (http://example.com, etc.).

I tried to do this by piecing suggestions together:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{HTTP_HOST} ^www\.garrysun\.com [NC]
RewriteRule ^(.*)$ https://garrysun.com/$1 [L,R=301]

But when I check the URL in a redirect checker I get errors... http://garrysun.com works fine and goes to https://garrysun.com but http://www.garrysun.com gets this:

Checked link: http://www.garrysun.com Type of redirect: 301 Moved Permanently Redirected to: https://garrysun.com/https://www.garrysun.com

How can I correct my rewrite code?

P.S. - I am using OpenCart 1.5.4 and I also have the following rewrite code above the new stuff (don't know if it affects anything):

RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

回答1:

You can use this single rule for that requirement:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://garrysun.com%{REQUEST_URI} [NE,L,R=301]

# rest of your rules will appear below