2016-02-05 93 views
0

我正在制作一个社交网站,它将拥有许多用户。因此,我需要一个更简单,更简单的方法来访问任何用户页面。假设我登录为Freddy,如果我去Freddy的个人资料页面,网址将会显示:http://localhost/profile_page.php。如果从这个页面开始,我想说,Alice的个人资料页面,我可以简单地修改网址并输入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(谁是真正的用户,因此我期望它会转到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 

回答

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_-]+)/$只能匹配字母,数字和下划线,因此例如问号不能匹配。

试试这个(assumming,与其profile.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这里为了增加网址的可读性(我看,也许你的意思是说明你的规格)

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 

在这种情况下,你将能够匹配这些URL * 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框架一样。