[英]htaccess url rewrite http www and non-www to https www + https non-www to https www
[英]301 redirects(.htaccess) - http to https + www to non-www + 'index.php' to '/'
我已經閱讀了很多關於 301 重定向(.htaccess)的文章,但沒有找到任何可以幫助我在這個問題的標題中提到的所有 3 個重定向的文章(http 到 https + www 到非 www + ' index.php' 到 '/')。
到目前為止我嘗試過的(但無法達到預期的結果):
.htaccess file
RewriteEngine on
#redirect http to https plus www to non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
#RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [NE,L,R=301]
#redirect /index.php to /
#RewriteRule ^index\.php$ / [L,R=301]
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 year"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
這工作正常,僅當涉及到http
到https
,但所有三個重定向都不能同時工作,如果我嘗試不同的解決方案,我會收到Error Too many redirects
您可以使用以下 htaccess
RewriteEngine on
#redirect http to https plus www to non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [NE,L,R=301]
#redirect /index.php to /
RewriteRule ^index\.php$ / [L,R=301]
編輯 :
如果您使用的是cloudflare
則需要將%{HTTPS}
變量替換為 Cloudflare url 方案檢查變量%{HTTP:CF-Visitor}
。
替換這一行
RewriteCond %{HTTPS} off [OR]
和
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
在測試此更改之前,請確保清除瀏覽器緩存。
嘗試這個 :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]
RewriteRule ^index\.php / [R=301,L]
上面的規則將匹配https://www
和http://www以及所有http://
並將它們強制轉換為https://without-wwww
並且只會忽略https://without-www
。
最后一行將刪除 URI 中的index
。
注意:清除瀏覽器緩存測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.