如何将动态URL转换为静态URL

rlc*_*rlc 7 php apache .htaccess

我正在使用PHP和Apache开发一个网站.我想转发我的网址

www.example.com/book.php?book=title

如果可能的话,当然可能是这样的:

www.example.com/book/title

请注意,书籍的标题是唯一的,不能重复.

我已经读到了这个,但是对于像我这样的初学者来说,这些帖子都不够清楚.你们知道任何解释这个的教程吗?

谢谢.

nik*_*org 0

Expanding on @Rodolphe's and @Galen's replies a little bit.

If your needs for url rewriting are limited, a hardcoded .htaccess with rules described in Rodolphe's example will do nicely.

However, as Galen suggests, your needs may be unknown, or you may want to expand on them later, without the need to touch your rewriting rules, once you have them working.

A common way to do it, is to design your application around a URL scheme which is www.host.com/controller/action/parameter. An example of such a URL could be www.host.com/book/view/1, which could then internally be handled in a number of ways.

1)

You have separate scripts for every controller. You then rewrite every request to the form $controller.php?action=$action&param=$param, redirecting non-matching or non-valid requests to a default controller.

# 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&param=$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]
Run Code Online (Sandbox Code Playgroud)

2)

You have a single entry point (or a front controller) to which you redirect every request, and this front controller handles redirecting the request to the appropriate controller.

# 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]
Run Code Online (Sandbox Code Playgroud)

The generic fallback rules will not append any parametes to the default/front controller. However, since it is an internal redirect, you will have access to the REQUEST_URI in PHP to determine what you should be doing.

These are, naturally, not your only options. Just my 2 cents in the soup to stir a bit more.

Disclaimer: All of the above rewrite rules (as well as everything else, of course) are written straight off the top of my head (after a few beers) and haven't been tested anywhere.