【问题标题】:Redirecting from /index.php to / not working从 /index.php 重定向到 / 不工作
【发布时间】:2016-12-29 06:42:56
【问题描述】:

我网站中的动态页面配置了以下 htaccess 规则:

# Dynamic Pages
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

所以页面被重定向到

http://example.com/?url=testpage

http://example.com/testpage/

但我也想将 /index.php 重定向到 / (root)。所以当有人进入时

http://example.com/index.php

在浏览器地址栏中应该转到

http://example.com/

为此,我尝试了以下规则:

#index.php to /
RewriteRule ^index\.php$ / [R=301]

虽然这工作正常,但它影响了我之前的 htaccess 规则。以及以下网址

http://example.com/testpage/

自动变成

http://example.com/?url=testpage

当我删除此规则时,之前的动态页面规则可以正常工作。如何让这两个规则在我的 htaccess 文件中正常工作而不会相互冲突?

我完整的 .htaccess 文件是:

Options +FollowSymlinks -MultiViews

#Enable mod rewrite
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d

# Dynamic Pages
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

# index.php to /
RewriteRule ^index\.php$ / [R=301]

【问题讨论】:

    标签: regex apache .htaccess redirect mod-rewrite


    【解决方案1】:

    您可以使用这些规则:

    Options +FollowSymlinks -MultiViews
    
    #Enable mod rewrite
    RewriteEngine On
    
    # index.php to /
    RewriteCond %{THE_REQUEST} /index\.php [NC]
    RewriteCond %{REQUEST_URI} ^(.*/)index\.php$ [NC]
    RewriteRule ^ %1 [L,R=301,NE]
    
    # Dynamic Pages
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* index.php?url=$0 [QSA,L]
    

    重要的是在第一条规则中使用THE_REQUEST,这样你就不会出现重写循环。清除浏览器缓存以进行测试。

    【讨论】:

    • 哇!即使我无法理解规则,这也很有效。
    • THE_REQUEST 变量代表 Apache 从您的浏览器收到的原始请求,并且在执行某些重写规则后它不会被覆盖。此变量的示例值为GET /index.php?id=123 HTTP/1.1
    猜你喜欢
    • 1970-01-01
    • 2014-08-31
    • 2020-05-02
    • 2021-09-21
    • 1970-01-01
    • 2018-04-03
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多