【问题标题】:htaccess rewrite rules and removing php file extensionhtaccess 重写规则并删除 php 文件扩展名
【发布时间】:2014-07-29 03:15:10
【问题描述】:

我的 htaccess 文件中有以下代码来删除 PHP 扩展:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

但是,现在我在 /directory/index.php 中添加了一个文件,我只能使用 /directory/index 而不是仅使用 /directory/ 访问它(现在会抛出 404 not found)。

【问题讨论】:

  • 你的 RewriteCond %{REQUEST_FILENAME} !-f 检查文件是否被请求并且存在,所以除非文件被请求并且存在,否则你的规则永远不会匹配任何东西。

标签: regex apache .htaccess mod-rewrite


【解决方案1】:

在根 .htaccess 中保留这样的规则:

DirectoryIndex index.php

RewriteEngine On
RewriteBase /

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

【讨论】:

  • 如果我不做分页并希望使用以下结构怎么办: domain.com/directory/example 有第一页结果,而分页将类似于 domain.com/directory/ example/page/2 我应该将这些规则放在托管 example.php 文件的目录下的新 htaccess 中吗?谢谢!
  • 其实这条规则与分页无关。它旨在根据您的问题隐藏 .php 扩展名。请发布一个具有分页要求的新问题,我将尝试相应地回答。
  • 完成,对此感到抱歉:) stackoverflow.com/questions/25030419/…
猜你喜欢
  • 2011-08-29
  • 2012-03-18
  • 2017-01-07
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多