簡體   English   中英

使用 .htaccess 將 http 重定向到帶有 www 的 https

[英]Redirect http to https with www using .htaccess

如何使用.htaccess將 HTTP 重定向到 https 包括 WWW?

例子 :

  1. http://example.com重定向到https://www.example.com
  2. http://www.example.com重定向到https://www.example.com
  3. https://example.com重定向到https://www.example.com

我想

RewriteEngine On

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

您可以將以下代碼放入.htaccess文件中

RewriteEngine On
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https 
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

這個.htaccess文件會將http://example.com/重定向到https://example.com/

代碼說明

  • [NC]匹配 URL 的大小寫版本
  • X-Forwarded-Proto (XFP) 標頭是用於識別協議的事實上的標准標頭
RewriteEngine On 
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80 //If you want the condition to match port
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

試試這個。 希望這可以幫助你。

嘗試這個

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

APACHE

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

NGINX

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /srv/www/example.com/keys/ssl.crt;
    ssl_certificate_key /srv/www/example.com/keys/www.example.com.key;
    return 301 https://www.example.com$request_uri;
}

你可以替換ssl; 指令與聽 443 ssl; 作為nginx 文檔的推薦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM