【问题标题】:Clean URLs with PHP [duplicate]使用 PHP 清理 URL [重复]
【发布时间】:2012-05-31 17:26:15
【问题描述】:

所以我正在尝试在 PHP 中构建一个干净的 url 系统,以将这样的 URL 更改为 http://example.com/index.php?projects=05 为:http://example.com/projects/05

到目前为止,我已经弄清楚如何使用parse_url 来映射看起来像http://example.com/index.php/projects/05 的网址,但我不知道如何从网址中删除“index.php”。有没有办法使用 .htaccess 从 url 字符串中删除 index.php

我知道这是一个简单的问题,但经过大量谷歌搜索后,我找不到解决方案。

【问题讨论】:

  • 你应该在 .htaccess 中使用 mod rewrite 将 /index.php 转换为 /。

标签: php http url url-mapping


【解决方案1】:

您需要在 Apache 中使用 mod_rewrite 执行此操作。您需要将所有 URL 重定向到您的 index.php,然后,也许使用 parse_url,弄清楚如何处理它们。

例如:

# Turn on the rewrite engine
RewriteEngine On

# Only redirect if the request is not for index.php
RewriteCond %{REQUEST_URI} !^/index\.php

# and the request is not for an actual file
RewriteCond %{REQUEST_FILENAME} !-f

# or an actual folder
RewriteCond %{REQUEST_FILENAME} !-d

# finally, rewrite (not redirect) to index.php
RewriteRule .* index.php [L]

【讨论】:

  • 我无法找到使用 .htaccess 自动重定向的方法 - 你能举个例子吗?
【解决方案2】:

我正在使用以下 .htaccess 文件来删除 url 的 index.php 部分。

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

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

RewriteRule .* index.php/$0 [PT]

否则我可以推荐 Kohana 框架作为参考(他们也有相当不错的 url 解析器和控制器系统)

【讨论】:

    【解决方案3】:

    将实际文件/文件夹与 URL 分离的概念称为 路由。许多 PHP 框架都包含这种功能,主要使用 mod_rewritePHP URL Routing 上有一篇不错的博文,它实现了一个简单的独立路由器类。

    它像这样创建映射:

    mysite.com/projects/show/1 --> Projects::show(1)
    

    所以请求的 URL 导致调用 Projects 类的函数 show(),参数为 1

    您可以使用它来构建漂亮的 URL 到 PHP 代码的灵活映射。

    【讨论】:

      【解决方案4】:

      在你的 .htaccess 中有这样的东西:

      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule ^(.*)$ index.php [QSA,L]
      

      (确保启用了重写模块)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 2023-04-07
        相关资源
        最近更新 更多