问题
I have a database of articles with the urls as follow:
person/albert-einstein/
(trailing slash)
person/albert-einstein/1
(no trailing slash)
And I was wondering what was the best way to handle url trailing slashes in Codeigniter 3?
This is what I have done/test so far:
echo site_url('person/albert-einstein/'); # http://localhost/person/albert-einstein
echo base_url('person/albert-einstein/'); # http://localhost/person/albert-einstein
echo site_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1
echo base_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1
Then I edited config.php
to set:
$config['url_suffix'] = '/';
and printed again the urls:
echo site_url('person/albert-einstein/'); # http://localhost/person/albert-einstein/
echo base_url('person/albert-einstein/'); # http://localhost/person/albert-einstein
echo site_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1/
echo base_url('person/albert-einstein/1'); # http://localhost/person/albert-einstein/1
Now I can select site_url()
or base_url()
to print the url with trailing slash or without it. But now on my views I have to be very careful to which one I use and I'd rather use a function that respects the url I pass and return it with trailing slash if it have or don't add one if it doesn't have it.
And yes, I can definitely extend the helper and write a function like: print_url()
that does what I want but I wanted to see if there's something I'm missing here. Thank you.
回答1:
You can use apache rewite rule for forcing trailing slash:
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
For removing trailing slash you can use:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
I used this good base of .htaccess
snippets.
来源:https://stackoverflow.com/questions/36524343/handle-trailing-slash-with-codeigniter-3