【问题标题】:how to remove the .php extension from url, for a file named same like a folder如何从 url 中删除 .php 扩展名,用于与文件夹名称相同的文件
【发布时间】:2016-04-06 18:31:57
【问题描述】:

我用过这段代码

## remove the php extention
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

这适用于某些文件,例如example.com/contact,但当我有一个也是目录的.php 文件时不起作用。例如,在根文件夹中:

science.php 
science - folder

文章属于类别,例如http://example.com/science/themost-blabla.php - 这行得通,.php 扩展不会出现在 URL 中。

所以我想知道是否有可能隐藏 .php 扩展至 science.php,因为当我输入 example.com/science 时……它会将我重定向到科学文件夹的内容……

/science 目录的索引:

  • afla-care-a-fost-primul-meci-televizat-de-fotbal-din-lume-1937-arsenal.php
  • cazinoul-din-constanta.php cele-7-minuni-ale-lumii.php
  • descoperire-colosala-a-epavei-navei-spaniole-san-jose-ce-avea-la-bord-o-avere-impresionanta.php
  • imagini/ mitologia-greaca.php poenaru.php
  • top-10-cele-mai-importante-inventii-romanesti-din-istorie.php
  • top-5-enigme-ale-lumii.php turnul-eiffel.php

那么,我可以做些什么来隐藏这个页面的扩展吗?还是我需要更改文件的名称 - 不是文件夹?

【问题讨论】:

  • 如果存在与文件同名的文件夹,则无法将url重写为文件。资源需要是唯一可识别的,如果您删除扩展名,情况就不再如此了。
  • 你可以将文件移动到science文件夹中并命名为index.php,这个解决方案也不需要url重写。
  • @CharlotteDunois “如果存在与文件同名的文件夹,则无法将 url 重写为文件。” - 嗯,你可以。 “文件夹”包含尾部斜杠,而文件不包含斜杠。但是,为了避免冲突,您需要设置DirectorySlash Off。
  • @w3dk 这样做会降低您的搜索引擎排名,因为带有和不带有斜杠的页面应该是相同的内容(最好将 301 从一个重定向到另一个以避免得到双重结果)。使用和不使用斜杠提供两种不同的结果是不好的做法,只会带来混乱。它还表明,如果您认为这是解决“问题”的方法,那么您作为开发人员的想法并不多。

标签: php .htaccess


【解决方案1】:

试试这个

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

【讨论】:

  • 嘿,我看了你的回答,然后我明白了。是我的错,谢谢指正....
  • 提供 OP 不需要访问裸目录(例如 science/)并且始终访问文件,那么如果您包含 DirectorySlash Off 指令(以防止 mod_dir 附加斜杠) 那么这个解决方案确实可以解决问题。
【解决方案2】:

其中一个“问题”是 mod_dir 在访问目录时会尝试通过在 URL 末尾附加一个斜杠来“修复”该 URL。但是,可以禁用此功能。

# Prevent mod_dir from automatically appending slashes to directories
DirectorySlash Off

# Disable directory listings
# In cases where there is a directory with no similar .php file and no DirectoryIndex
Options -Indexes

# If a PHP file exists for the requested URL then rewrite to this
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule (.*) $1.php [L]

如果需要,可以通过在 URL 上显式附加斜杠来访问裸目录(或者更确切地说,DirectoryIndex)。例如。 example.com/science/。但是,这可能是不必要的(并且最好避免以避免用户混淆),因为我假设 example.com/science(没有尾部斜杠,即science.php)返回您的“科学”类别内容。如果没有 DirectoryIndex 文档,example.com/science/ 将简单地返回 403 Forbidden。或者,您可以使用外部重定向从此类 URL 中显式删除尾部斜杠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2020-03-19
    • 2013-03-14
    相关资源
    最近更新 更多