php 如何从网站地址中删除文件扩展名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6534904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:39:45  来源:igfitidea点击:

How can I remove file extension from a website address?

phpurl-rewritingfriendly-url

提问by Sumit Gupta

I am designing a website. I want my website address to look like the following image:

我正在设计一个网站。我希望我的网站地址如下图所示:

File name extensions like (PHP/JSP) are hidden

像 (PHP/JSP) 这样的文件扩展名被隐藏

I don't want my website to look like http://something.com/profile.php. I want the .phpextension to be removed in the address bar when someone opens my website. In other words, I want my website to be like: http://something.com/profile

我不希望我的网站看起来像http://something.com/profile.php. .php当有人打开我的网站时,我希望在地址栏中删除扩展程序。换句话说,我希望我的网站是这样的:http: //something.com/profile

As a second example, you can look at the Stack Overflow website address itself.

作为第二个示例,您可以查看 Stack Overflow 网站地址本身。

How can I get this done?

我怎样才能做到这一点?

回答by Igor

Just add an .htaccess file to the root folder of your site (for example, /home/domains/domain.com/htdocs/) with the following content:

只需将 .htaccess 文件添加到您站点的根文件夹(例如,/home/domains/domain.com/htdocs/),内容如下:

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

回答by Shiv Singh

First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.

首先,验证是否安装了 mod_rewrite 模块。然后,小心理解它是如何工作的,很多人把它倒退了。

You don't hide urls or extensions. What you do is create a NEW url that directs to the old one, for example

您不会隐藏网址或扩展程序。例如,您要做的是创建一个指向旧网址的新网址

The URL to put on your web site will be yoursite.com/play?m=asdf

放在您网站上的 URL 将是 yoursite.com/play?m=asdf

or better yet

或者更好

yoursite.com/asdf

yoursite.com/asdf

Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:

即使目录 asdf 不存在。然后安装了 mod_rewrite,你把它放在 .htaccess 中。基本上它说,如果请求的 URL 不是文件也不是目录,请将其定向到我的脚本:

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /play.php [L] 

Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same ORcreate a database table that correlates the "SEO friendly URL" with the product id. An example might be

差不多完成了 - 现在您只需要在 PHP 脚本中编写一些内容来解析新的 URL。你想这样做,以便旧的也能工作——你所做的是维护一个变量始终完全相同的系统,或者创建一个将“SEO 友好 URL”与产品 ID 相关联的数据库表。一个例子可能是

/Some-Cool-Video (which equals product ID asdf)

/Some-Cool-Video(等于产品 ID asdf)

The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?

这样做的好处?搜索引擎会将关键字“Some Cool Video”编入索引。空军?谁会去寻找那个?

I can't give you specifics of how to program this, but take the query string, strip off the end

我不能给你如何编程的细节,但是拿查询字符串,去掉结尾

yoursite.com/Some-Cool-Video 

turns into "asdf"

变成“asdf”

Then set the m variable to this

然后将 m 变量设置为此

m=asdf

m=asdf

So both URL's will still go to the same product

所以两个 URL 仍然会指向同一个产品

yoursite.com/play.php?m=asdf 
yoursite.com/Some-Cool-Video 

mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)

mod_rewrite 也可以做很多其他重要的事情,谷歌搜索它并在您的服务器上激活它(它可能已经安装。)

回答by Iman Hejazi

You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

你有不同的选择。其中之一是创建一个名为“profile”的文件夹,并将您的“profile.php”重命名为“default.php”并将其放入“profile”文件夹中。您可以通过这种方式向此页面发出命令:

Old page: http://something.com/profile.php?id=a&abc=1

旧页面:http: //something.com/profile.php?id=a&abc=1

New page: http://something.com/profile/?id=a&abc=1

新页面:http: //something.com/profile/?id=a&abc=1

If you are not satisfied leave a comment for complicated methods.

如果您不满意,请对复杂的方法发表评论。

回答by Dan Horvat

Actually, the simplest way to manipulate this is to

实际上,操纵它的最简单方法是

  1. Open a new folder on your server, e.g. "Data"
  2. Put index.php (or index.html) in it
  1. 在您的服务器上打开一个新文件夹,例如“数据”
  2. 将 index.php(或 index.html)放入其中

And then the URL www.yoursite.com/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.com/data/list run that PHP file.

然后 URL www.yoursite.com/data 将读取该 index.php 文件。如果您想更进一步,请在其中打开一个子文件夹(例如“List”),将另一个 index.php 放入该文件夹中,您可以让 www.yoursite.com/data/list 运行该 PHP 文件。

This way you can have full control over this, very useful for SEO.

这样您就可以完全控制它,这对 SEO 非常有用。

回答by Rahul Singh

The problem with creating a directory and keeping index.php in it is that

创建目录并在其中保留 index.php 的问题在于

  1. your links with menu will stop functioning
  2. There will be way too many directories. For eg, there will be a seperate directory for each and every question here on stackoverflow
  1. 您与菜单的链接将停止运行
  2. 会有太多的目录。例如,stackoverflow 上的每个问题都会有一个单独的目录

The solutions are 1. MOD REWRITE (as suggested above) 2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/

解决方案是 1. MOD REWRITE(如上所述) 2. 使用 php 代码在索引文件中动态包含其他文件。在这里阅读更多内容http://inobscuro.com/tutorials/read/16/

回答by Tony

Here is a simple PHP way that I use.
If a page is requested with the .php extension then a new request is made without the .php extension. The .php extension is then no longer shown in the browser's address field.

这是我使用的一种简单的 PHP 方式。
如果使用 .php 扩展名请求页面,则会发出不带 .php 扩展名的新请求。.php 扩展名不再显示在浏览器的地址字段中。

I came up with this solution because none of the many .htaccess suggestions worked for me and it was quicker to implement this in PHP than trying to find out why the .htaccess did not work on my server.

我想出了这个解决方案,因为许多 .htaccess 建议都不适合我,而且在 PHP 中实现它比试图找出为什么 .htaccess 在我的服务器上不起作用更快。

Put this at the beginning of each PHP file (preferrably before anything else):

把它放在每个 PHP 文件的开头(最好放在其他任何东西之前):

include_once('scripts.php');  
strip_php_extension();  

Then put these functions in the file 'scripts.php':

然后将这些函数放在文件“scripts.php”中:

//==== Strip .php extension from requested URI  
function strip_php_extension()  
{  
  $uri = $_SERVER['REQUEST_URI'];  
  $ext = substr(strrchr($uri, '.'), 1);  
  if ($ext == 'php')  
  {  
    $url = substr($uri, 0, strrpos($uri, '.'));  
    redirect($url);  
  }  
}  

//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)  
{  
  if (!headers_sent())  
  {  
    /* If headers not yet sent => do php redirect */  
    header('Location: '.$url);  
    exit;  
  }  
  else  
  {
    /* If headers already sent => do javaScript redirect */  
    echo '<script type="text/javascript">';  
    echo 'window.location.href="'.$url.'";';  
    echo '</script>';  

    /* If javaScript is disabled => do html redirect */  
    echo '<noscript>';  
    echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';  
    echo '</noscript>';  
    exit;  
  }  
}  

Obviously you still need to have setup Apache to redirect any request without extension to the file with the extension. The above solution simply checks if the requested URI has an extension, if it does it requests the URI without the extension. Then Apache does the redirect to the file with the extension, but only the requested URI (without the extension) is shown in the browser's address field. The advantage is that all your "href" links in your code can still have the full filename, i.e. including the .php extension.

显然,您仍然需要设置 Apache 将任何没有扩展名的请求重定向到带有扩展名的文件。上面的解决方案只是检查请求的 URI 是否有扩展名,如果有,则请求没有扩展名的 URI。然后 Apache 重定向到带有扩展名的文件,但浏览器的地址字段中仅显示请求的 URI(不带扩展名)。优点是代码中的所有“href”链接仍然可以具有完整的文件名,即包括 .php 扩展名。

回答by Ravinder Kumar

Remove a file extension through .htaccess:

通过.htaccess删除文件扩展名:

Original URL: http://ravinderrathore.herobo.com/contact.php

原文网址:http: //ravinderrathore.herobo.com/contact.php

.htaccess rule to remove .php, .html, etc. file extensions from URLs:

从 URL 中删除 .php、.html 等文件扩展名的 .htaccess 规则:

RewriteRule ^(.*)$ .php

After Rewriting: http://ravinderrathore.herobo.com/contact

重写后:http: //ravinderrathore.herobo.com/contact

RewriteEngine on

RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/

RewriteRule ^index(.*)?$ index.php [L,QSA]

RewriteRule ^login_success(/)?$ login_success.php [L,QSA]

RewriteRule ^contact(/)?$ contact.php [L,QSA]

回答by Jon

same as Igor but should work without line 2:

与 Igor 相同,但应该在没有第 2 行的情况下工作:

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

回答by Jon

Tony, your script is ok, but if you have 100 files? Need add this code in all these :

托尼,你的脚本没问题,但如果你有 100 个文件呢?需要在所有这些中添加此代码:

include_once('scripts.php');
strip_php_extension();

include_once('scripts.php');
strip_php_extension();

I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D

我认为您在每个 php 文件中都包含一个菜单(可能您的菜单显示在所有网页中),因此您只能在菜单文件中添加这两行代码。这对我有用:D

回答by Güney Saramal?

For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.

对于那些仍在寻找简单答案的人;您可以使用删除文件扩展名,.htaccess但此解决方案只是节省了一天,甚至可能不会。因为当用户从地址栏中复制 URL 或尝试重新加载甚至从历史记录中返回时,您的标准 Apache 路由器将无法意识到您在寻找什么并向您抛出一个404 Error. 为此,您需要一个专用的路由器,通过说出服务器和文件系统不知道的内容,使您的应用程序了解 URL 的实际含义。

I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,jsand phpfiles even more like imagesor whatever you have.

我在这里留下我的解决方案。这已经为我的客户和我的项目进行了多次测试和使用。它也支持多语言和语言检测。推荐阅读自述文件。它还提供你一个很好的结构与differenciated语言文件整洁的项目(你甚至可以为每种语言不同的设计)和分离cssjs以及php文件更像images或者任何你拥有。

Cr8Router - Simple PHP Router

Cr8Router - 简单的 PHP 路由器