如何减少301重定向的数量?

时间:2017-12-13 22:55:23

标签: apache .htaccess redirect mod-rewrite http-status-code-301

对于我的网站,我想强制使用https的URL,不带www,不带.php扩展名。 为此,我的htaccess文件包含以下规则:

RewriteEngine On

#force HTTPS and remove the www
RewriteCond %{SERVER_PORT} 80 [OR]
RewriteCond %{HTTP_HOST}  ^www\.jvincent\.fr$ [NC]
RewriteRule ^(.*) https://jvincent.fr/$1 [QSA,L,R=301]

#To remove the .php extension
RewriteCond %{REQUEST_URI} !(php-script) [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\ (.*)\.php [NC]
RewriteRule ^ %1 [R=301,L]

工作正常。 但是如果我使用网址http://www.jvincent.fr/phpinfo.php访问我的网站,我有两个301重定向:

  1. http://www.jvincent.fr/phpinfo.phphttps://jvincent.fr/phpinfo.php
  2. https://jvincent.fr/phpinfo.phphttps://jvincent.fr/phpinfo
  3. 我搜索了但是我无法找到优化的解决方案,并且在所有情况下只有一个301重定向。 我有办法做到这一点吗?在一个独特的RewriteRule之前合并所有条件?使用环境变量(第一部分中的标志E)?

    感谢您的帮助。

    杰克

1 个答案:

答案 0 :(得分:0)

您可以使用:

RewriteEngine On

#force HTTPS and remove the www
RewriteCond %{SERVER_PORT} 80 [OR]
RewriteCond %{HTTP_HOST}  ^www\.jvincent\.fr$ [NC]
RewriteRule ^(.*?)(?:\.php)?$ https://jvincent.fr/$1 [NC,QSA,L,R=301]

#To remove the .php extension
RewriteCond %{REQUEST_URI} !(php-script) [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\ (.*)\.php [NC]
RewriteRule ^ %1 [R=301,L]