【问题标题】:.htaccess Rewrite .php to 'virtual folder' [duplicate].htaccess 将 .php 重写为“虚拟文件夹”[重复]
【发布时间】:2012-08-21 17:56:03
【问题描述】:

可能重复:
remove .php extension with .htaccess

我有

http://www.example.com/test/categoryform.php

在我的 .htaccess 文件中,如何重写以显示为:

http://www.example.com/test/categoryform/

【问题讨论】:

  • 欢迎来到 SO。在提出问题之前,请先使用搜索并自己进行一些研究。不是我们不喜欢你的问题,只是这个问题已经被问过和回答过,所以没有必要再问了。您可能会看到一些不赞成票,因为它经常被问到,所以您犯了一些常见的错误,这会在这个网站上引发一些情绪。但无论如何,欢迎来到 SO。
  • 我做了一些研究,但我的问题是由其他原因引起的(需要 RewriteBase,几乎没有人提及)
  • 当然,RewriteBase 在 HTTPD 手册中有很好的解释:httpd.apache.org/docs/current/mod/mod_rewrite.html - 正如您所看到的,它甚至与 RewriteCond 和 RewriteRule 以及 RewriteEngine 在同一页面上。

标签: php .htaccess rewrite


【解决方案1】:

简单的问题问了thousand

RewriteEngine on
RewriteBase /test/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

来源:Removing file extension via .htaccess

【讨论】:

  • 我认为它超过 9000...您应该指向 cmets 中的重复项而不是回答。
  • 我知道这一点。问题是,没有一个建议对我有用。我一直收到 404 错误。但是我刚刚发现这是因为我需要将 RewriteBase 声明为`RewriteBase /test/。还是谢谢。
  • @MichaelGeorgeCrothers:只是不要在不了解其作用的情况下从其他来源复制和粘贴代码。至少如果遇到问题,首先要开始理解它。
  • 我标记了它(带有适当的副本)并回答了问题。我不知道这样做是一种“惯例”,并且无法在常见问题解答中找到它,现在想起来这不是我第一次看到它。
  • PS,我编辑它以供将来参考,检查这是你拥有它的方式。
【解决方案2】:

为了去除尾部斜线,你需要在一个条件中匹配它

RewriteEngine On
# make sure it's not a directory or a file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# match out the request URI without the trailing slash
RewriteCond %{REQUEST_URI} ^/([^/]+?)/?$
# and see if it exists
RewriteCond %{DOCUMENT_ROOT}/%1.php -f

RewriteRule ^(.+?)/?$ /$1.php [L]

但为了让它显示(如显示在浏览器的地址栏中,你需要:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+?)\.php
RewriteRule ^(.+?)\.php$ /$1/ [L,R=301]

【讨论】:

    【解决方案3】:

    试试这个代码

    RewriteEngine On
    # turn on the mod_rewrite engine
    
    RewriteCond %{REQUEST_FILENAME}.php -f
    # IF the request filename with .php extension is a file which exists
    RewriteCond %{REQUEST_URI} !/$
    # AND the request is not for a directory
    RewriteRule (.*) $1\.php [L]
    # redirect to the php script with the requested filename
    

    How to hide .php extension in .htaccess的问题也很有用

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 2014-05-22
      • 2013-10-08
      • 2021-11-20
      • 2014-01-13
      • 2011-08-05
      相关资源
      最近更新 更多