HTACCESS使用HTTPS重定向添加WWW

Uda*_*ale 4 apache .htaccess mod-rewrite redirect url-rewriting

目前我的htaccess代码是

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


#send all traffic to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Run Code Online (Sandbox Code Playgroud)

这在输入以下网址时有效

1. https://example.com -> https://www.example.com
2. http://example.com -> https://www.example.com
3. http://www.example.com -> https://www.example.com
4. https://example.com -> https://www.example.com
5. https://example.com/somepage -> https://www.example.com/somepage
6. http://www.example.com/somepage -> https://www.example.com/somepage

但是当尝试访问某个页面时,https和www都不存在时,它不起作用,而是重定向到奇怪的URL

7. http://example.com/somepage -> https://www.example.com/https://example.com/somepage

有什么建议?

Jus*_*man 8

用这个替换你当前的代码

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
Run Code Online (Sandbox Code Playgroud)

注意:也许您必须清除浏览器的缓存才能看到它的工作原理 http://example.com/somepage