URL重写(路由),mod_rewrite,或PHP

URL rewrite (routing), mod_rewrite, or PHP

我想自己解决这个问题,但没有成功。

我有一个网站(PHP,Apache),具有以下结构,作为示例:

1. http://hostname/ 
2. http://hostname/category?list=listname 
3. http://hostname/product?id=...&name=productname 
4. http://hostname/recipes 
5. http://hostname/recipe?id=...&name=recipename

+ many others.

当前的 .htaccess 是:

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

例如 http://hostname/category?list=... 变成 /category.php?list... 然后它捕获 php 脚本并运行。

我想创建这样的友好 URL:

1. http://hostname/ 
2. http://hostname/category/listname/
3. http://hostname/product/productname/
4. http://hostname/recipes/
5. http://hostname/recipe/recipename/

另一方面,以前的网址必须仍然有效,因为网站已被搜索引擎大量索引。因此,它必须从旧式网址 301 重定向到新网址。 有任何想法吗? 我所有的努力都有错误。我什至尝试通过 index.php 入口点进行 PHP 路由,但我不知道如何处理旧式链接。

首先,如果 multiviews 已启用,请将其禁用。尝试以下规则以启用 301 重定向到新的 url 结构:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET\ /(category|product|recipe)(?:\.php)?\?.*(name|list)=([^&\s]+) [NC]
RewriteRule ^ /%1/%3/? [R=301,L,NC]

至于 local/internal 重定向回实际页面,必须单独处理:

RewriteRule ^(category)/([^/]+)/?$ /.php?list= [NC,L]
RewriteRule ^(recipe|product)/([^/]+)/?$ /.php?name= [NC,L]
RewriteRule ^(recipe)/?$ /.php [NC,L]