我刚刚开始学习PHP,并从YouTube上关于mvc的教程开始。一切都很顺利,但是当我开始开发自己的应用程序时,我遇到了路由问题(我认为)。
我的基本应用程序有URL:localhost/mvc/public/。
在本教程中,我创建了一个类,该类在未指定时启动默认的主控制器和索引操作。所以localhost/mvc/public/等同于localhost/mvc/public/home/index。
在我看来,我有:
<p>You need to <a href="profile/login">log in</a> or <a href="profile/register">register</a></p>
因此,当我从url localhost/mvc/public/开始,然后单击一个链接时,它会转到localhost/mvc/public/profile/login,一切正常。但是,如果我写url localhost/mvc/public/home/index,然后单击一个链接,我会转到localhost/mvc/public/home/profile/index,这显然不起作用。所以我的问题是 - 如何解决这个问题?
如果有人感兴趣,我可以发布我的代码。
profile/register
是相对路径,因此它被添加到您已有的路径中。由于/home/index
没有尾随/
,浏览器假定home
是路径,index
是文件或资源名称,因此保留home
并向其添加profile/register
。
解决方案:将链接中的路径更改为/profile/register
(带有前导/
)。开头的/
告诉浏览器在裸域名后添加路径,而不是选择相对于当前路径的路径。
可能更好:为您的应用程序添加一个"基本路径"设置,通过它知道基本路径是什么。在代码中,您可以在生成路径时使用此基路径,例如:
<a href="<?=$basepath?>profile/register">
如果在根目录中安装了应用程序,则可以将 basepath 设置为 /
。在您的情况下,您可以将其设置为 /mvc/public/
.
您也可以为其创建一个函数来包装设置,而不是变量。如果你搜索"CodeIgniter基本路径",你会发现很多关于CodeIgniter(一个流行的MVC框架)如何处理这个问题的例子。