301重定向(.htaccess)-http到https + www到非www +'index.php'到'/'

时间:2019-03-21 17:18:15

标签: php apache .htaccess redirect

我浏览了很多有关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>

仅当涉及到httphttps时,此方法才能正常工作,但是所有三个重定向均无法一次工作,如果尝试不同的解决方案,则会得到Error Too many redirects

2 个答案:

答案 0 :(得分:1)

您可以使用以下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]

在测试此更改之前,请确保清除浏览器缓存。

答案 1 :(得分:0)

尝试一下:

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://wwwhttp://www以及所有http://并将其强制进入https://without-wwww,并且还将仅忽略https://without-www

最后一行将删除URI中的index

注意:清除浏览器缓存测试