Site URLs using a PHP "pretty url" framework
I have been experimenting with the lightweight NiceDog PHP routing framework, which routes like this:
R('entries/(?<id>\d+)')
->controller('Entries_Controller')
->action('show')
->on('GET')
Now the .htaccess
file is set up to do this redirect like so:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
My problem is when I want to make a URL to somewhere, it seems impossible to do so.
Say I've requested the page entries/5
, and on that page I would like to link to another entry entries/6
:
<a href="entries/6">Next Entry</a>
This resolves to the address http://localhost/folder/to/project/entries/5/entries/6
The href /entries/6
would link to http://localhost/entries/6
To work around this,开发者_运维技巧 I created a function to handle this problem:
function url($route) {
return "http://localhost/folder/to/project/$route";
}
So I can now write
<a href="<?= url('entries/6') ?>">Next Entry</a>
which now links to http://localhost/folder/to/project/entries/6
, which is exactly what I want.
However, I have to do this for EVERY in-site link, and it seems like there could be a better solution that doesn't involve an externally created URL.
Is there a "better" way to fix this problem? Is this a "common" problem with PHP frameworks? (It seems it would be)
The easy alternative would be to use <base href="http://example.org/your/project/index" /> in your page templates <head>. But that's basically like having full URLs generated. And yes, it's also valid for XHTML and still in HTML5.
I don't know about NiceDog but other frameworks I have used have a built in function that can convert a route to the corresponding URL.
For example in Symfony this would look something like:
<a href="<?php echo url_for('entries/show?entry=5') ?>">Link Text</a>
The routing system will then reverse resolve this into the URL relative to any root you set in the config.
Could you use:
RewriteBase /folder/to/project/
in your htaccess file making
RewriteEngine On
RewriteBase /folder/to/project/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
精彩评论