【问题标题】:PHP URL Format without .php extension?没有.php扩展名的PHP URL格式?
【发布时间】:2019-06-15 01:22:41
【问题描述】:

我只需要在不显示 PHP 文件名的情况下获取一个字符串作为 URL。我有文件 contact.php 页面我正在尝试获取 URL 例如

localhost/contact.php

这就是我现在得到的,我需要访问这个页面

本地主机/联系人

对于每个页面,我应该只能通过他们的名字来导航。

本地主机/联系人
本地主机/帮助
本地主机/支持

【问题讨论】:

  • mod_rewrite 和 .htaccess 是你的朋友

标签: php mod-rewrite url-rewriting


【解决方案1】:

如果您使用的是 apache,则需要使用 .htaccess 文件。如果您使用的是 IIS,那么您可以在 IIS 中进行配置。

看看this

您的.htaccess 文件需要如下所示:

IndexIgnore * # prevent directory listing

Order deny,allow
Allow from *

# ------------------------------------------
# Rewrite so that php extentions are not shown
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

由于文件限制,您不能简单地在 Windows 中创建 .htaccess 文件,因此请打开文本编辑器(记事本 ++ 或您的编程 IDE)并创建一个名为 .htaccess 的新文件。 . 在文件名前面很重要。

编辑

不要有重复的文件名。 IE contact.phpcontact.js 作为 htaccess 将不知道要提供哪个服务,哪个(取决于您的 apache)要么返回错误页面,要么只提供其中一个。

正如@AedixRhinedale 在下面的 cmets 中指出的那样:

来自Apache 的注释:如果您有权访问 httpd 主服务器配置文件,则应完全避免使用 .htaccess 文件。使用 .htaccess 文件会降低 Apache http 服务器的速度。您可以在 .htaccess 文件中包含的任何指令都最好设置在 Directory 块中,因为它具有相同的效果并具有更好的性能

【讨论】:

  • 在您的答案中添加来自Apache 的注释:如果您有权访问 httpd 主服务器配置文件,则应完全避免使用.htaccess 文件。使用 .htaccess 文件会降低 Apache http 服务器的速度。可以在.htaccess 文件中包含的任何指令都最好设置在Directory 块中,因为它具有相同的效果并具有更好的性能。
  • @AedixRhinedale 谢谢我将其添加到答案中并将注释归功于您:)。我其实不知道
  • 当我把我的网站上线的时候呢! @JacquesKoekemoer
  • 好吧,如果您使用共享主机,您可能无法访问 httpd 文件,因此请将 .htaccess 复制到您的代码根目录中
  • 太棒了。谢谢 :) @JacquesKoekemoer
【解决方案2】:

就这么简单..

1) 在目录中创建 .htaccess 文件(windows 对此有限制,如上所述)。

2) 只需插入这个..

# Turn mod_rewrite on
RewriteEngine On

##(Optional) Redirects http to https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#### hiding .php extensions below:

# (optional) Ignore logic.php .. any page that is needed as mvc with .php exstensions 
RewriteCond %{THE_REQUEST} ^/logicpath/logic.php [NC]
RewriteCond %{THE_REQUEST} ^/logicpath/funcs.php [NC]
# (optional end ^)

## To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]


# (optional) Does the same for html paths
## To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R,L,NC]
## To internally redirect /dir/foo.html to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.php [L]
# (optional end ^)

如前所述,httpd 主服务器配置文件要好得多。我不太确定如何解决主要配置文件,但我知道从小经验来看并不完全一样。

如果其他人知道学习如何修改配置文件的好资源,请提及!

【讨论】: