【问题标题】:How to reduce the number of 301 redirect?如何减少301重定向的次数?
【发布时间】:2018-05-27 22:51:38
【问题描述】:

对于我的网站,我想强制使用带有 https、不带 www 且不带 .php 扩展名的 URL。 为此,我的 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]

它工作正常。 但是,如果我使用 URL 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

我进行了搜索,但找不到优化的解决方案,并且在所有情况下都只有一个 301 重定向。 我有办法吗?在唯一的 RewriteRule 之前合并所有条件?使用环境变量(第一部分中的标志 E)?

感谢您的帮助。

杰克

【问题讨论】:

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


    【解决方案1】:

    你可以使用:

    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]
    

    【讨论】:

    • 太好了!非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2019-07-31
    • 2018-12-15
    • 1970-01-01
    • 2010-12-21
    • 2012-04-25
    • 1970-01-01
    相关资源
    最近更新 更多