我正在使用PHP和Apache开发一个网站。 我想转发我的网址
www.example.com/book.php?book=title
如果有可能的话,就像这样:
www.example.com/book/title
请注意,图书的标题是唯一的,不能重复。
我已经读过这篇文章,但是对于像我这样的初学者来说,这些帖子都不够清楚。 你们知道任何解释这个问题的教程吗?
感谢。
答案 0 :(得分:3)
这是kohana(以及99%的php框架)的方式
添加.htaccess文件(如果使用apache)
# Turn on URL rewriting
RewriteEngine On
RewriteBase /
# 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/URL
RewriteRule .* index.php/$0 [PT,L]
这会将所有网址重定向到index.php。 index.php将是某种基于url加载脚本的前端控制器
所以在你的例子中:
本地主机/书/标题
将加载index.php。它将进入url并获取页面(控制器)加载,实际上将完成所有工作。在这种情况下可能是books.php。 books.php将从网址获取图书的标题,然后搜索数据库或使用该名称执行任何操作。
答案 1 :(得分:3)
我已经在静态格式中创建了一个内部链接,例如我的网页中的“http://www.example.com/casestudy/34”。
我在.htaccess文件中写了以下代码:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^casestudy/([^-]+) /casestudy_details.php?id=$1 [R=301,QSA,L]
答案 2 :(得分:2)
您正在寻找的功能称为“网址重写”。
您可以手动执行此操作:使用正则表达式解释模式,Web服务器会转换请求。 使用Apache,它通常位于htaccess文件或httpd.conf中的directyl下。 见官方文件。在这里:http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
虽然设置起来并不容易,但特别是调试正则表达式。
关于您的问题,请尝试以下规则:
RewriteEngine on
RewriteRule ^book/(.*)$ book.php?book=$1 [L]
另一种选择是使用php框架:大多数时候,这个功能都是内置的。 你必须“学习”如何使用框架。如果您的网站已经完成,这不是最佳选择...
答案 3 :(得分:0)
大多数解决方案都依赖于mod_rewrite。 See here例如。
答案 4 :(得分:0)
扩大@ Rodolphe和@Galen的回复。
如果您对网址重写的需求有限,那么使用Rodolphe示例中描述的规则的硬编码.htaccess
将会很好。
然而,正如Galen建议的那样,您的需求可能是未知的,或者您可能希望稍后对其进行扩展,而无需触及您的重写规则,一旦您让它们工作。
执行此操作的常用方法是围绕www.host.com/controller/action/parameter
的URL方案设计应用程序。此类网址的示例可以是www.host.com/book/view/1
,然后可以通过多种方式在内部进行处理。
1)
每个控制器都有单独的脚本。然后,您将每个请求重写为$controller.php?action=$action¶m=$param
格式,将不匹配或无效的请求重定向到默认控制器。
# Serve files and directories as per usual,
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
# If the request uri doesn't end in .php
# and isn't empty, rewrite the url
RewriteCond %{REQUEST_URI} !.php$
RewriteCond %{REQUEST_URI} !^$
# Try matching against a param request first
RewriteRule (.*?)/(.*?)/(.*?) $1.php?action=$2¶m=$3 [L]
# If it didn't match, try to match an action
RewriteRule (.*?)/(.*?) $1.php?action=$2 [L]
# redirect all other requests to index.php,
# your default controller
RewriteRule .* index.php [L]
2)
您有一个入口点(或前端控制器),您可以将每个请求重定向到该入口点,此前端控制器会处理将请求重定向到相应的控制器。
# Redirect all requests that isn't a file or
# directory to your front controller
RewriteCond %{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} !-d
RewriteRule .* index.php [L]
通用回退规则不会将任何参数附加到默认/前端控制器。但是,由于它是内部重定向,因此您可以访问PHP中的REQUEST_URI
以确定您应该执行的操作。
这些当然不是您唯一的选择。只需2美分的汤就可以搅拌一下。
声明: 所有上述重写规则(当然还有其他所有规则)都是直接写在我的头顶上(经过一些啤酒之后)并且没有在任何地方进行过测试。