重写规则不起作用或无法正确呈现页面


Rewrite Rule not working or rendering page properly

我正在制作一个社交网站,它将拥有许多用户。因此,我需要一种更简单、更轻松的方式来访问任何用户页面。假设我以弗雷迪的身份登录,如果我转到弗雷迪的个人资料页面,网址会说:http://localhost/profile_page.php。如果从这个页面,我想去,比方说,爱丽丝的个人资料页面,我可以简单地修改网址并键入http://localhost/profile_page.php/alice而不是写http://localhost/profile_page.php?u=alice

我创建了一个.htaccess文件,并在Wamp中启用了Apache模块rewrite_module。但是,页面无法正确加载。同样,假设我以 Freddy 身份登录,个人资料页面加载完美,但是当我编辑 url 以转到另一个用户页面时,即 http://localhost/profile_page.php/Alice(谁是真实用户,所以我希望它转到爱丽丝的个人资料页面(,它不会按照 CSS 的指示呈现页面,并且还停留在 Freddy 的个人资料页面上。

.htaccess

RewriteBase /www/
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?u=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?u=$1

好吧,你的规则没有考虑这里的php文件(检查我是否在规则中的所有正则表达式之前添加了斜杠(:

RewriteBase /www/
RewriteEngine On
RewriteRule ^/([a-zA-Z0-9_-]+)$ profile.php?u=$1
RewriteRule ^/([a-zA-Z0-9_-]+)/$ profile.php?u=$1

使用这段代码,http://localhost/profile_page.php?u=alice 将永远不匹配。 ^([a-zA-Z0-9_-]+)/$仅匹配字母、数字和下划线,因此例如问号无法匹配。

试试这个(假设不是个人资料.php你的意思是profile_page.php

RewriteBase /www/
RewriteEngine On
RewriteRule ^/profile_page.php/([a-zA-Z0-9_-]+)$ profile_page.php?u=$1
RewriteRule ^/profile_page.php/([a-zA-Z0-9_-]+)/$ profile_page.php?u=$1

另一个改进。只能在一个表达式中设置两个表达式。

RewriteBase /www/
RewriteEngine On
RewriteRule ^profile_page.php/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1

我强烈建议您在此处删除profile_page.php以提高 url 的可读性(我明白了,也许您在规范中的意思是这种格式(。

RewriteBase /www/
RewriteEngine On
RewriteRule ^/profile_page.php/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1
RewriteRule ^/profile/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1
RewriteRule ^/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1

在这种情况下,您将能够匹配这些网址* http://localhost.com/alice* http://localhost:com/profile/alice* http://localhost.com/profile_page.php/alice

为了能够匹配您自己的配置文件,只需确保为此启用一些路由,例如:

RewriteBase /www/
RewriteEngine On
RewriteRule ^/?$ profile_page.php
RewriteRule ^/me?$ profile_page.php
RewriteRule ^/profile_page.php/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1
RewriteRule ^/profile/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1
RewriteRule ^/([a-zA-Z0-9_-]+)/?$ profile_page.php?u=$1

检查此处的顺序是否重要。第一个匹配,第一个应用。在这种情况下,我使用了相同的终结点文件。检查是否设置了 $_GET['u'] 以加载指定的用户或会话中的用户。

我强烈建议您使用某种前端控制器,以便能够管理给定一个类(例如app.php的所有路由(,就像Symfony或任何现代PHP框架一样。