.htaccess重写合并

问题描述 投票:1回答:1

我目前在.htaccess文件中有两个重写规则,现在需要添加另一个。但是,GTMetrix已经在这里给我一个F评级,说明:避免登陆页面重定向

  1. 第一个重定向将www.添加到URL。
  2. 第二个重定向将一个子目录添加到URL。
  3. 第三个(建议的)重定向将https添加到URL的开头。
RewriteEngine on

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Then, rewrite to /catalog
RewriteCond %{REQUEST_URI} !^/catalog [NC]
RewriteRule ^(.*)$ /catalog/$1 [L]

#Now, rewrite to HTTPS:
#RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

有没有办法将这些组合成一个重定向?或者,着陆页重定向不是那么糟糕吗?

.htaccess redirect mod-rewrite
1个回答
1
投票

您的第1和第3个重定向规则可以合并为一个,并且应该在重写规则之前保留:

RewriteEngine On

# add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

#Then, rewrite to /catalog
RewriteCond %{REQUEST_URI} !^/catalog/ [NC]
RewriteRule ^(.*)$ /catalog/$1 [L]

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

© www.soinside.com 2019 - 2024. All rights reserved.