CodeIgniter .htaccess and base_url() issues
-
16-06-2021 - |
Question
I started working on CodeIgniter recently and I'm having some issues with the .htaccess and the base_url() function causing issues. I hope this is just a noob error and has a quick fix!
Pretty much what happens is that now with the .htaccess the index.php is gone from the url which is amazing but now I am having issues linking stylesheets and js files with my templates.
In all the tutorials I have read/watched, they have included the .htaccess and then still set their base_url() and then using "link_tag(href);" to link their .css but now I am getting a double up on the url. For instance when I tried to add the stylesheet, the path that it looked for was:
http://www.mysite.com/site/www.mysite.com/site/css/stylesheet.css
So my first thought was just to remove my base_url() so that the .htaccess does everything but it doesn't work. With the .htaccess I can have a site without the index.php being there but without stylesheets or JavaScript files linked or I can have a site with some styling, but deal with the index.php. There must be a way that both will work simultaneously?
Also, I did a fix by instead of using the link_tag() I just echoed out a normal link tag which works perfectly in the beginning when its still:
http://www.mysite.com/
But if the login is incorrect and I redirect to load the login view again, the styling disappears because its now using the relative path from:
http://www.mysite.com/user/login
Thanks in advance! Any help would be appreciated.
La solution
Try
RewriteEngine on
RewriteCond $1 !^(css|js)
RewriteRule ^(.*)$ /index.php/$1 [L]
So www.mysite.com/css/mycss.css
is retrieved normally where as www.mysite.com/something
is passed to codeigniter.
To get the css file with base_url()
you would do base_url("css/mycss.css")
, which should result in "http://www.mysite.com/css/mycss.css"
Autres conseils
A better .htaccess ruleset would be:
#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
This disallows access to your system and applications folder, but allows access to all other files, for example: /js/*, /css/*, /img/*, etc.