使用“干净网址”时使用相对网址?
我将所有 url 请求定向到前端控制器。 url 请求类似于 example.com/controller/action/etc
。问题是,在程序中使用相对网址。如果 url 请求中只有一个斜杠,则此方法可以正常工作,但如果有多个斜杠,则相对 url 就会损坏。
在位置 example.com/controller
处,相对 URL other-controller
可以很好地将用户带到 example.com/other-controller
。
在位置 example.com/controller/action
处,相对网址 other-controller
无法将用户引导至 example.com/controller/other-controller< /代码>。
关于如何解决这个问题有什么建议吗?希望每次我想在应用程序中创建 url 时,我都可以做到这一点,而无需使用绝对路径或某些 url 生成代码。
如果重要的话,我目前正在使用这个 .htaccess 代码将传入请求重定向到前端控制器:
# Point all to index.php except existing files
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
I direct all url requests to a front controller. The url requests look something like example.com/controller/action/etc
. The problem is, using relative urls within the program. This works fine if there is only one slash in the url request, but if there is more than one slash, the relative url becomes broken.
At location example.com/controller
, relative url other-controller
works fine taking the user to example.com/other-controller
.
At location example.com/controller/action
, relative url other-controller
doesn't work taking the user to example.com/controller/other-controller
.
Any recommendations on how to get around this? Hoping I can do this without using absolute paths or some url generating code everytime I want to make a url in the app.
In case it matters, I am currently using this .htaccess code to redirect incomming requests to the front controller:
# Point all to index.php except existing files
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将需要使用绝对 URL 来执行您想要的操作,而无需查看当前所在的路径并添加适当数量的
..
。您不需要为每个控制器都提供域,只需使用/controller/action
和/other-controller/action
等 URL。这些将无缝地适用于两个控制器。锚标记示例:顺便说一句,人们通常会编写函数来生成 URL。如果您使用的是 MVC 框架,则可能采用向模型添加方法并调用函数
get_absolute_url
的形式,该函数返回我上面提到的形式。You're going to need to use absolute URLs to do what you want without looking at the current path you are at and adding the proper number of
..
s. You don't need to have the domain for each one, you can just use URLs like/controller/action
and/other-controller/action
. These will work for both controllers seamlessly. A sample anchor tag:As a side note, oftentimes, people will write functions to generate URLs. If you are using a MVC framework, it may be in the form of adding a method to a model and call the function
get_absolute_url
which returns the form I mentioned above.