首页 > 解决方案 > 重定向 301 到 / 如果 url 包含 index.php

问题描述

我在 laravel 5.8 中有一个博客,我想将 301 重定向到 / 它的 url 中有 index.php。

我的 .htaccess 是这个

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle www + https
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # Redirect if index.php is in the URL
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

我试过这种方法:

    # Redirect if index.php is in the URL
    RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
    RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

但问题是如果有一个像这样的 url 包含 (?get_params)

htts://www.example.com/index.php?test

它将 301 重定向到 /?test

如果 url 包含 index.php ,如何更改规则以将 301 重定向到 / (没有任何?参数)?

标签: phpapache.htaccessredirectmod-rewrite

解决方案


您可以使用QSD 标志(查询字符串丢弃)来重定向而不传递查询字符串。

当请求的 URI 包含查询字符串而目标 URI 不包含时,RewriteRule 的默认行为是将该查询字符串复制到目标 URI。使用 [QSD] 标志会导致查询字符串被丢弃。

# Redirect if index.php is in the URL
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php /$1 [R=301,NE,L,QSD]

推荐阅读