1

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.

gglasses
  • 826
  • 11
  • 30

1 Answers1

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.

Tpojka
  • 6,996
  • 2
  • 29
  • 39
  • Thank you for your interest on my question but remember that I use `urls` **with** trailing slash and **without** trailing slash for different sections of my site. So your solution using `mod_rewrite` doesn't really apply to this question my friend. :-) – gglasses Apr 10 '16 at 00:56
  • I followed this request: "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". First snippet allows it. – Tpojka Apr 10 '16 at 00:59