【问题标题】:Removing index.php from website URLs从网站 URL 中删除 index.php
【发布时间】:2010-10-28 15:34:21
【问题描述】:

我正在使用 Kohana 框架(但我认为这与这个问题无关)并且可以像这样访问页面

http://www.example.com/articles/
http://www.example.com/index.php/articles/

现在,根据经验,我通常会尝试调整我的 .htaccess 以仅允许页面的一种进入方式,并静默重定向其他常用方式。

本质上,在上面的第一个 URL 中,地址实际上是在内部重定向到第二个示例。

我想要做的是强制任何第二种类型的 URL 变成第一种类型的 URL。我通常对 .htaccess 没有信心,我的第一次尝试是抛出一些意想不到的结果(比如有时会出现无限循环)

这是我想出来的

RewriteRule ^index\.php/(.*) $1 [NC,L,R=301]

谁能告诉我我做错了什么,如果你也遇到这个问题,你是怎么解决的?

编辑

我决定发布我的整个 .htaccess,以便可以检查我的所有重定向。

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /~toberua/


# file not found page
    ErrorDocument 404 /404/
    ErrorDocument 403 /403/

# get people out of my directories
    Options -Indexes

# default page to load
    DirectoryIndex index.php

# add trailing slash if missing
    RewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]

# redirect /favicon.ico requests
     RewriteCond %{REQUEST_URI} !^/images/layout/favicon\.ico [NC]
     RewriteCond %{REQUEST_URI} favicon\.(gif|ico|png|jpe?g) [NC]
     RewriteRule (.*) images/layout/favicon.ico [R=301,L]

# send /home back to TLD
     RewriteRule home/ $1  [NC,R=301,L]

# ensure there is no /index.php in the address bar
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.php\ HTTP/
    RewriteRule ^(.*)index\.php$ $1 [R=301,L] # this was my attempt to stop /dir/index.php and make it simply /dir/

    RewriteRule ^index\.php/(.*) $1 [NS,NC,L,R=301]

# Protect application and system files from being viewed
RewriteRule ^(application|modules|system) - [F,L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT,L]

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting friendly-url


    【解决方案1】:

    试试这个:

    RewriteRule ^index\.php/(.*) $1 [NS,NC,L,R=301]
    

    您没有处理的是 所有 请求都需要重写,并且当您进行重写时,它会生成一个子请求——这也需要重写。因此,您最终将 /articles 重写为 /index.php/articles,然后在该问题的子请求中,您将 /index.php/articles 重写为 /articles 并生成一个新的 301 重定向请求,不断重复。添加 NS 标志将使该规则不适用于子请求,我认为这应该可以解决您的问题,除非您还在 /articles -> /index.php/articles 重写上执行 301(但这将是疯狂的)。

    【讨论】:

    • 回应您的编辑:您认为我需要设置 RewriteCond 吗?我尝试添加该标志,但它仍在循环。有什么建议?为您的麻烦 +1 :)
    • 我不认为 RewriteCond 是必要的或有用的,不。如果没有看到您用于将 /articles/ 重写为 /index.php/articles 的规则,我无法理解为什么会发生持续循环。
    • 让我再补充一些问题。
    • 是的,添加 NS 肯定会停止循环。这是在 .htaccess 中,还是在 vhost conf 文件中,或者您可能忘记踢 Apache 以使修改后的规则到位?
    • 我搞定了 混乱!我在 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php(.*)\ HTTP/ [NC] 上面添加了这一行
    猜你喜欢
    • 2015-09-06
    • 2018-02-09
    • 2015-12-14
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2016-05-14
    • 2014-10-28
    相关资源
    最近更新 更多