gpt4 book ai didi

php - 如何在 PHP 中重写 URL?

转载 作者:IT王子 更新时间:2023-10-29 00:07:40 25 4
gpt4 key购买 nike

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

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

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

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

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

还有一点,从 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

最佳答案

A Beginner's Guide to mod_rewrite .

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

只是为了好玩,这里有一个 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/$0 [PT,L]

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

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

www.mysite.com/jokes

public function jokes ($page = 1) {
# Show Joke Page (Defaults to page 1)
}

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

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

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

关于php - 如何在 PHP 中重写 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1039725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com