【发布时间】:2012-02-28 09:57:44
【问题描述】:
如果您访问如下网址:http://stackoverflow.com/questions/9155602/,地址栏将更新为http://stackoverflow.com/questions/9155602/redirect-existing-file-to-different-url-using-mod-rewrite。这不是用 JavaScript 完成的,也不是用硬刷新完成的,我最好的猜测是它是用 mod_rewrite 完成的;但是,如果不使用php进行服务器端处理,它怎么知道文章的标题?
我刚刚更新了我的网站以使用 SEO 友好的 url,它曾经是 /shows.php?id=review-1,现在是 /review/1/super-baseball-2020。最后的文字实际上并不重要,因为我的重写是:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9]+)/([0-9]+)/([a-z0-9-]+)?/?$ /shows.php?id=$1-$2 [L,NC]
我目前确保 Google 不会因为重复内容而打击我并且书签被正确转发的路径如下:
RewriteCond %{THE_REQUEST} ^GET\s/shows\.php\?
RewriteCond %{QUERY_STRING} (?:^|&)id=review-1(?:&|$) [NC]
RewriteRule ^ /review/1/super-baseball-2020/? [R=301,L,NC]
RewriteCond %{THE_REQUEST} ^GET\s/shows\.php\?
RewriteCond %{QUERY_STRING} (?:^|&)id=review-2(?:&|$) [NC]
RewriteRule ^ /review/2/aero-fighters-2/? [R=301,L,NC]
RewriteCond %{THE_REQUEST} ^GET\s/shows\.php\?
RewriteCond %{QUERY_STRING} (?:^|&)id=review-3(?:&|$) [NC]
RewriteRule ^ /review/3/aero-fighters-3/? [R=301,L,NC]
.... and so on ....
该解决方案非常短视,需要在我的 .htaccess 中放入数千行代码。
【问题讨论】:
-
我怀疑这个功能是在 SO 上使用
mod_rewrite完成的。发生的情况是,对 stackoverflow.com/*anything* 的任何请求都由相同的服务器端代码处理,然后解析该 URL 并将您的请求路由到为页面内容提供服务的代码使用问题 ID。问题标题被服务器忽略,尝试访问stackoverflow.com/questions/9168364/bouncing-fluffy-muffins -
通常 mvc 应用程序会将所有传入请求路由到同一个脚本(前端控制器),该脚本将解析请求本身,并将操作委托给适当的控制器类。
标签: php .htaccess mod-rewrite redirect url-rewriting