【问题标题】:URL rewrite (routing), mod_rewrite, or PHPURL 重写(路由)、mod_rewrite 或 PHP
【发布时间】:2015-12-31 11:03:24
【问题描述】:

试图自己解决,但没有运气。

我有一个网站(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 ^(.*)$ $1.php 

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

我想制作这样的友好网址:

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 路由,但我不知道如何处理旧式链接。

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-redirection friendly-url


    【解决方案1】:

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

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

    至于本地/内部重定向回实际页面,必须单独处理:

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

    【讨论】:

    • 感谢您的帮助。 RewriteCond %{THE_REQUEST} ^GET\ (category|product|recipe)(?:\.php)?\?.*(name|list)=([^&\s]+) [NC] 只能在没有 ^GET\ 的情况下工作。不能禁用多视图,托管设置不允许这样做。其他一切都按预期工作。在这些情况下是什么导致 [NC] 和 [L]?
    • NC 表示匹配大写/小写字母。 L 表示不处理进一步的规则。在此处阅读有关标志的更多信息:devdocs.io/apache_http_server/rewrite/flags@Zergius2 我错过了RewriteCond 中的领先/
    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多