如何在 PHP 中进行 URL 重写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1039725/
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-25 00:44:36  来源:igfitidea点击:

How to do URL re-writing in PHP?

phpapachemod-rewriteseourl-rewriting

提问by Prashant

I am trying to implement URL rewriting in my PHP application. Can someone share a step by step procedure of implementing URL rewriting in PHP and MySQL?

我正在尝试在我的 PHP 应用程序中实现 URL 重写。有人可以分享在 PHP 和 MySQL 中实现 URL 重写的分步过程吗?

In my application I want to implement following URL rewriting, I want to redirect

在我的应用程序中,我想实现以下 URL 重写,我想重定向

1. http://example.com/videos/play/google-io-2009-wave-intro
2. http://example.com/videos/play/203/google-io-2009-wave-intro

to

1. http://example.com/videos/play.php?title=google-io-2009-wave-intro
2. http://example.com/videos/play.php?id=203

Please tell me how to implement both URL rewriting in any of the above way.

请告诉我如何以上述任何一种方式实现两种 URL 重写。

One more thing which URL will be best according to SEO, management, application point-of-view out of the following two types.

根据SEO,管理,应用程序的观点,以下两种类型中哪个URL是最好的另一件事。

1. http://example.com/videos/play/google-io-2009-wave-intro
2. http://example.com/videos/play/203/google-io-2009-wave-intro

回答by Sampson

A Beginner's Guide to mod_rewrite.

mod_rewrite 的初学者指南

Typically this will be nothing more than enabling the mod_rewrite module (you likely already have it enabled with your host), and then adding a .htaccess file into your web-directory. Once you've done that, you are only a few lines away from being done. The tutorial linked above will take care of you.

通常,这只不过是启用 mod_rewrite 模块(您可能已经在主机上启用了它),然后将 .htaccess 文件添加到您的 web 目录中。一旦你这样做了,你离完成只有几行了。上面链接的教程会照顾你。

Just for fun, here's a Kohana.htaccess file for rewriting:

只是为了好玩,这里有一个用于重写的Kohana.htaccess 文件:

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /rootDir/

# Protect application and system files from being viewed
RewriteRule ^(application|modules|system) - [F,L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/
RewriteRule .* index.php/
public function jokes ($page = 1) {
  # Show Joke Page (Defaults to page 1)
}
[PT,L]

What this will do is take all requests and channel them through the index.php file. So if you visited www.examplesite.com/subjects/php, you may actually be visiting www.examplesite.com/index.php?a=subjects&b=php.

这将做的是获取所有请求并通过 index.php 文件引导它们。因此,如果您访问了 www.examplesite.com/subjects/php,您实际上可能正在访问 www.examplesite.com/index.php?a=subjects&b=php。

If you find these URLs attractive, I would encourage you to go one step further and check out the MVC Framework (Model, View, Controller). It essentially allows you to treat your website like a group of functions:

如果您发现这些 URL 很有吸引力,我鼓励您更进一步查看 MVC 框架(模型、视图、控制器)。它本质上允许您将您的网站视为一组功能:

www.mysite.com/jokes

www.mysite.com/jokes

public function jokes ($page = 1) {
  # Show Page 2 of Jokes (Page 2 because of our different URL)
}

Or, www.mysite.com/jokes/2

或者,www.mysite.com/jokes/2

RewriteRule ^videos/play/([0-9]+)/([^.]+)$ play.php?id=&name=

Notice how the first forward slash calls a function, and all that follow fill up the parameters of that function. It's really very nice, and make web-development much more fun!

注意第一个正斜杠如何调用一个函数,后面的所有内容都填充了该函数的参数。这真的非常好,让网络开发变得更加有趣!

回答by Evert

You cannot do this with PHP alone. You'll need to look into mod_rewrite (assuming you are using apache).

单独使用 PHP 无法做到这一点。您需要查看 mod_rewrite (假设您使用的是 apache)。

回答by pjau

Using mod rewrite:

使用 mod 重写:

RewriteEngine On
RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/([-0-9a-zA-Z]+)/?$ //.php?id= [L]

example.com/play.php?id=203&name=google-io-2009-wave-intro

example.com/play.php?id=203&name=google-io-2009-wave-intro

would work as

将作为

example.com/videos/play/203/google-io-2009-wave-intro

example.com/videos/play/203/google-io-2009-wave-intro

回答by Andrew Sledge

Keep in mind that redirecting is not the same as rewriting.

请记住,重定向与重写不同。

A redirect is when the server receives the request and the response is sent as a redirect. For instance, you request a page www.example.com/page. When the server receives this, either the page or the server self issues a redirect command to the browser. The redirect command basically says "go here: new page". In PHP, this is in the form of header('Location: newpage.html');

重定向是当服务器收到请求并且响应作为重定向发送时。例如,您请求一个页面 www.example.com/page。当服务器收到此消息时,页面或服务器自身会向浏览器发出重定向命令。重定向命令基本上是说“去这里:新页面”。在 PHP 中,这是采用 header('Location: newpage.html'); 的形式。

A rewrite is when the server receives the request from the browser then looks in a list of matching regular expressions for that site. If a match is found, the URL is rewritten into that form and is responded to accordingly. For instance, the requested URL www.example.com/specificpage could be rewritten (on the server end) as www.example.com/?loadpage=specificpage. The browser never receives header information stating that it must go somewhere else.

重写是指服务器收到来自浏览器的请求,然后在该站点的匹配正则表达式列表中查找。如果找到匹配项,则将 URL 重写为该形式并相应地做出响应。例如,请求的 URL www.example.com/specificpage 可以(在服务器端)重写为 www.example.com/?loadpage=specificpage。浏览器永远不会收到表明它必须去其他地方的标头信息。

回答by jeroen

If your server supports it (apache / mod_rewrite), you can use a .htaccess file to re-direct the visitor.

如果您的服务器支持它 (apache / mod_rewrite),您可以使用 .htaccess 文件来重定向访问者。

Something like (just a draft, adapt to your own needs...):

像(只是一个草稿,适应你自己的需要......):

<?php
// Here you can parse the current location
// and decide whenever you want to go
// if $_SERVER[ 'PHP_SELF'] some conditions then....
header('Location: http://www.example.com/');
?>

for the second example.

对于第二个例子。

回答by Steve Claridge

You could approach this slightly differently from the suggestions above by using a Front Controller, it's a common solution for making custom URLs and is used in all languages, not just PHP. Here's a guide: http://www.oreillynet.com/pub/a/php/2004/07/08/front_controller.html

您可以通过使用 Front Controller 来处理与上述建议略有不同的方法,它是制作自定义 URL 的常见解决方案,可用于所有语言,而不仅仅是 PHP。这是一个指南:http: //www.oreillynet.com/pub/a/php/2004/07/08/front_controller.html

Essentially you would create an index.php file that is called for every URL, its job is to parse the URL and determine which code to run based on the URL's contents. So, for example a user would use a URL such as http://example.com/index.php/videos/play/203/google-io-2009-wave-introand index.php would extract the remaining elements from the URL (/videos/play/203/google-io-2009-wave-intro) take the first part, load a php file with that name (videos.php or you can make it use play.php) and pass through the parameters 203 and google-io.

本质上,您将创建一个为每个 URL 调用的 index.php 文件,它的工作是解析 URL 并根据 URL 的内容确定要运行的代码。因此,例如,用户将使用诸如http://example.com/index.php/videos/play/203/google-io-2009-wave-intro 之类的 URL,而 index.php 将从URL (/videos/play/203/google-io-2009-wave-intro) 作为第一部分,加载具有该名称的 php 文件(videos.php 或者您可以使用 play.php)并传递参数203 和 google-io。

It's effectively doing the same thing as rewriting the code in mod_rewrite but does have a few benefits:

它与在 mod_rewrite 中重写代码有效地做同样的事情,但确实有一些好处:

  1. Doesn't require too much mod_rewrite code if you are new to that.
  2. Allows you to put all security code in one place - in index.php
  3. It's easy to change URLs and handle 404s etc.
  1. 如果您是新手,则不需要太多 mod_rewrite 代码。
  2. 允许您将所有安全代码放在一个位置 - 在 index.php 中
  3. 更改 URL 和处理 404 等很容易。

You can remove index.php from the URL using mod_rewrite, see here: http://www.wil-linssen.com/expressionengine-removing-indexphp/

您可以使用 mod_rewrite 从 URL 中删除 index.php,请参见此处:http: //www.wil-linssen.com/expressionengine-removing-indexphp/

回答by Artem Barger

After reading comments and question once again, I've realized that my previous answer is not completely the thing your are looking for. So here some additions, if you want rewrite/redirect/proxy the URL addresses so for example then user types www.f1.com he will actually see www.f2.com, but domain will remain the same, you probably need to setup a reverse proxyusing Apache for that. It act's similar to mod_rewrite.

再次阅读评论和问题后,我意识到我之前的答案并不完全是您想要的。所以这里有一些补充,如果你想重写/重定向/代理 URL 地址,例如然后用户输入 www.f1.com 他实际上会看到 www.f2.com,但域将保持不变,你可能需要设置一个使用 Apache 的反向代理。它的行为类似于 mod_rewrite。

Regarding the second part, since modern crawler also performing the URL link analyses I think your first option is better performance wise.

关于第二部分,由于现代爬虫也执行 URL 链接分析,我认为您的第一个选择是更好的性能明智的。

Previous answer:
And using PHP you can achieve redirection like:

上一个答案:
使用 PHP 可以实现如下重定向:

<Directory "/home/www/html">
    RewriteEngine On
    RewriteBase /
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php/%{REQUEST_URI} [PT,L]
</Directory>

From php.net. Heremore examples.

来自php.net这里有更多例子。

回答by Carlos Lima

Sorry about not giving you detailed explanation, but maybe you could take a look at DokuWikifor a starting point.

很抱歉没有给你详细的解释,但也许你可以看看DokuWiki作为一个起点。

In its setup it accepts 3 modes:

在其设置中,它接受 3 种模式:

  1. Regular urls: ?id=zzz
  2. .htaccess rewrite: uses apache to do the rewritting
  3. internal (php) rewrite: urls end up looking like http://www.example.com/kb/doku.php/start
  1. 常规网址:?id=zzz
  2. .htaccess 重写:使用 apache 进行重写
  3. 内部 (php) 重写:url 最终看起来像http://www.example.com/kb/doku.php/start

It's free so you can just download and browse the code.

它是免费的,因此您只需下载和浏览代码即可。

As a note, the apache redirect is very likely the best solution but the pure php one is also interesting in case your code is going to run in IIS6 servers where rewritting is not as easy as in apache.

请注意,apache 重定向很可能是最佳解决方案,但纯 php 重定向也很有趣,以防您的代码将在 IIS6 服务器中运行,而在 IIS6 服务器中重写不像在 apache 中那么容易。

回答by Poldon

Unfortunately, it's really up to the web server, not PHP. Depending on if you use Apache or something else, it has to do this before your script is executed. I use mod_rewrite, and an example rewrite rule looks like this:

不幸的是,这实际上取决于 Web 服务器,而不是 PHP。取决于您是使用 Apache 还是其他东西,它必须在执行脚本之前执行此操作。我使用 mod_rewrite,示例重写规则如下所示:

##代码##

The above rule basically says if the URL is a valid path to a real file or directory, load it. Otherwise, run it through index.php.

上面的规则基本上是说如果 URL 是真实文件或目录的有效路径,则加载它。否则,通过 index.php 运行它。