The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

Slim and htaccess / mod_rewrite issue

Juanes's Avatar

Juanes

26 Jun, 2012 09:40 AM

I'm having trouble making Slim work with this specific project, the folder structure is like this:

project
- src (main source files) - vendor (some libraries) - webroot (webroot js files images etc)

In the webroot folder I'm using the default .htaccess file that ships with Slim:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

And when the server's document root is set to project/webroot everything runs fine. But I'm currently unable to change the document root in the production server and so it is the project/ folder. So I created this .htaccess file there:

RewriteEngine On
RewriteRule    ^$    webroot/    [L]
RewriteRule    (.*) webroot/$1    [L]

This is supposed to redirect everything to the webroot folder, and it does, but Slim will always show the / route, even if the requested route does not exist.

/ -> loads / /route-does-not-exist -> loads / /route-exists -> loads /

I tried different htaccess settings but I haven't been able to make it work, can anyone give some advice?

  1. Support Staff 1 Posted by Andrew Smith on 26 Jun, 2012 09:52 AM

    Andrew Smith's Avatar

    In the Slim .htaccess file add this after RewriteEngine On

    RewriteBase /project/
    

    That should fix your issue.

  2. 2 Posted by Juanes on 26 Jun, 2012 10:14 AM

    Juanes's Avatar

    Thanks Andrew, but that didn't work at all.

    the project folder turns out to be the servers DocumentRoot and when I add the rewrite base directive like that I only get a server error.

    I also tried adding RewriteBase / and RewriteBase /webroot in the web root's folder .htaccess file but that didn't work either.

  3. Support Staff 3 Posted by Andrew Smith on 26 Jun, 2012 10:25 AM

    Andrew Smith's Avatar

    Which directory is the server webroot pointing to? which folder is your index.php in? can you show an example of the structure in a tree diagram way please? e.g.

    webroot
        project
            index.php <-- Slim Index
            src
            vendor
    
  4. 4 Posted by Juanes on 26 Jun, 2012 10:34 AM

    Juanes's Avatar

    Sure,

    Project -> server webroot
        - htaccess
        src
        vendor
        webroot
            - htaccess
            - index.php -> Slim Index
            - css, js, img etc
    

    When I change the server webroot to be Project/webroot it works fine, but I can't change that in production in the server webroot is Project/

  5. Support Staff 5 Posted by Andrew Smith on 26 Jun, 2012 10:54 AM

    Andrew Smith's Avatar

    In the webroot .htaccess on your server put this:

    RewriteEngine On
    RewriteBase /webroot/
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    
  6. 6 Posted by Juanes on 26 Jun, 2012 11:03 AM

    Juanes's Avatar

    I still have the same issue, it will always load the / route, even when requesting routes that don't exist at all.

    request / -> loads /
    request /admin -> loads /
    request /does-not-exist -> loads /
    request /foo/bar -> 404 Page Not Found
    

    I'm not an htaccess expert but I'm using a similar setup for my cakephp apps with our problem, I don't get why Slim keeps loading always the / route.

  7. Support Staff 7 Posted by Andrew Smith on 26 Jun, 2012 11:06 AM

    Andrew Smith's Avatar

    I have tested this locally and I don't get the issue you are getting either, what version of Slim are you currently on and can I have a look at your index.php file?

  8. 8 Posted by Juanes on 26 Jun, 2012 11:32 AM

    Juanes's Avatar

    I was using 1.6 but I just updated to 1.6.4 and I still have this issue. My php version is 5.3.6.

    The index.php file in the project/webroot folder looks like this:

    require __DIR__ . '/../src/app.php';
    

    I can't post the full app.php code, but it likes something like this:

    $app->get('/', function() use ($app) {
        $app->render('index.php');
    })->name('coupon');
    
    $app->post('/', function() use ($app) {
        // some code here
    });
    
    $app->get('/download/:code', function($code) use ($app) {
        // some code here
    });
    
    $app->get('/admin/', function() use ($app) {
        $app->render('admin/login.php');
    });
    
  9. 9 Posted by Juanes on 26 Jun, 2012 03:55 PM

    Juanes's Avatar

    I created a simple application just to test this.

    Root/
        - src/
            - .htaccess (#1)
            - app.php
        -vendors/
            -Slim/
        -webroot/
            - .htaccess (#2)
            - index.php
    

    The .htacccess (#1) file looks like this:

    RewriteEngine On
    RewriteBase /webroot/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    The app.php file:

    require __DIR__ . '/../vendor/Slim/Slim.php';
    
    $app = new Slim();
    
    $app->get('/', function() use ($app) {
        echo '/';
    })->name('coupon');
    
    $app->get('/admin/', function() use ($app) {
        echo '/admin';
    });
    
    $app->run();
    

    The index.php file:

    require __DIR__ . '/../src/app.php';
    

    And the .htaccess (#2) file:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
    

    Here is what happens, when the server document root is set to the webroot folder everything runs fine.

    When the server document root is set to the Root folder weird things happen.

    If I browse to / then the / route works, as expected. If I browse to /admin then the / route in slim is loaded again instead of /admin (?). If I load /abcd (which doesn't exist) then the / route is loaded again (?).

    This happens with routes with up to 7 chars even if they don't exist. If I load /1234567 it will still display the / route, but /12345678 will 404 as I would expect.

    So I created a new route in the app.php file:

    $app->get('/12345678', function() use ($app) {
        echo '/12345678';
    });
    

    And now when I open /12345678 I still get a 404 error (?).

    I'm doing this on OS 10.7.4 using a default MAMP installation with PHP 5.3.6 and Slim 1.6.4.

    Can anyone reproduce this?

  10. 10 Posted by Juanes on 27 Jun, 2012 05:07 PM

    Juanes's Avatar

    This is definitely a bug in Slim 1.6. The same code with the 1.5 version works just fine.

    I didn't have the chance to debug it yet but the problem seems to be in the way Slim handles the $SERVER['REQUEST_URI'] and $SERVER['SCRIPT_NAME'] in the Environment class.

  11. 11 Posted by Juanes on 29 Jun, 2012 02:02 PM

    Juanes's Avatar

    I tracked this one to the Environment class line 142. It seems like $env['SCRIPT_NAME'] is set to /webroot instead of / that's what I would expect.

    The 7 characters weird behavior I described is in fact the strlen($env['SCRIPT_NAME']) value which causes the script to set the route to /.

    I would appreciate if someone could check this one. I think running slim in a folder and using mod_rewrite like I described in the example is pretty common plus it works just fine in version 1.5.

  12. Support Staff 12 Posted by Andrew Smith on 29 Jun, 2012 03:25 PM

    Andrew Smith's Avatar

    We will take a look into this and get back to you.

  13. Support Staff 13 Posted by Brian Nesbitt on 06 Jul, 2012 01:42 PM

    Brian Nesbitt's Avatar

    As discussed here:
    http://help.slimframework.com/discussions/problems/769-url-routing-...

    I'm not convinced this is a bug. I'm also not sure why you would install a Slim app into a physical, public subdirectory but access it with a request URI that did not include the physical sub-directory path in the request URI. Can you? Sure. Why would you? I'm not really sure.

    I recommend that you either install Slim into the root of your virtual host. If you choose to install it into a physical sub-directory, then the physical path to the app must be present in the request URI for Slim to parse the request URI properly.

    I'll use your suggestions and run some tests this weekend to see what I can do without breaking existing apps.

  14. 14 Posted by George Goudie on 17 Jul, 2012 04:16 PM

    George Goudie's Avatar

    While maybe not a bug, it does reduce flexibility; CakePHP allows you to have a webroot subdirectory and it helps organise your code better

  15. 15 Posted by bslavin on 16 Mar, 2013 01:13 AM

    bslavin's Avatar

    I'm having a similar issue. My project structure looks like this:

    Root/                           (the server's web root)
         .htaccess (#1)
         public/
              .htaccess (#2)
              index.php
         Slim/
    

    The first .htaccess file contains the following:

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !public/
    RewriteRule (.*) public/$1 [L]
    

    The second .htaccess file contains the following:

    RewriteEngine On
    RewriteBase /public/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    The index.php file is really basic:

    require '../Slim/Slim.php';
    \Slim\Slim::registerAutoloader();
    $app = new \Slim\Slim();


    // Default GET route $app->get('/', function () { echo "Default GET route"; });


    // Hello World route $app->get('/hello/:name', function ($name) { echo "Hello, $name"; });


    $app->run();

    I'm having the same issue as Juanes with the 7 chars (mine is 6 due to using the directory name "public" instead of "webroot"). Here are some URLs so you can see how it works:

    http://brs.aws.af.cm/ => uses the default GET route
    http://brs.aws.af.cm/hello/john => 404 Error
    http://brs.aws.af.cm/public/hello/john => works, but requires "/public" in the url

    http://brs.aws.af.cm/123456 => shouldn't work, but uses the default GET route
    http://brs.aws.af.cm/1234567 => 404 Error

    I would like to structure the project this way rather than have the Slim/ directory in the web root. Any progress on this issue? Thanks.

  16. 16 Posted by Atom on 09 May, 2013 09:14 PM

    Atom's Avatar

    I am having the same issue as bslavin. Is there an update on this or a quick fix?

  17. Support Staff 17 Posted by Andrew Smith on 09 May, 2013 09:17 PM

    Andrew Smith's Avatar

    I think Brian outlined what the issue is above. Is the setup necessary for you to use Slim, why not just move it outside of document root?

  18. 18 Posted by Heath Morrison on 13 May, 2013 05:27 PM

    Heath Morrison's Avatar

    I believe I'm experiencing the same issue. I've written a detailed analysis of the issue I see in Environment.php in a Github ticket:

       https://github.com/codeguy/Slim/issues/521

    ...I would appreciate any feedback on my analysis.

  19. 19 Posted by Remy on 24 Jul, 2013 02:00 PM

    Remy's Avatar

    I have searched board for a solution for my problem but unfortunately I see several identical issues. They all seem to have the 'subdirectory problem'.

    My configuration has a main domain with several subdirs that are controlled by the htaccess file.

    So,
    www.maindomain.com/site1
    www.maindomain.com/site2
    www.maindomain.com/site3
    are available via
    www.site1.com
    www.site2.info
    www.site3.com

    On my current test which uses the slim framework I only see the main index when visiting www.site1.com, the /page1, page2, ect don't show. Everything works when going via www.maindomain,com/site1/page1

    I use the above setup for small sites, sometimes no more than just one page. But as mentioned earlier in this topic and at other places the routing just shows the main '/' page. It's a shame because I feel the Slim framework would be perfect for this situations.

    I know there is (was?) an advice to use slim only in the root dir. But hat doesn't work for me. Also I've see some info on using the virtualhost but that's somehow complex because I do most in the plesk panel. Besides, to me this more technical workaround seem contrary to the main idea of a simple framework.

    Perhaps I do something wrong here.
    But hopefully this issue gets a better solution

  20. 20 Posted by Heath Morrison on 24 Jul, 2013 04:02 PM

    Heath Morrison's Avatar

    Hi Remy,

    Yes, I think you and I have the same problem with Slim.

    I posted my ticket (#521) on Github, but the maintainer (codeguy) closed it without really responding to my concerns.

    Honestly, after my own analysis, I came to the conclusion that it is a bug in the code and in the test that confirms the code. I patched it locally in order to allow me to move on with my own project, and haven't thought about it much since then.

    -Heath

  21. 21 Posted by asilva on 26 Aug, 2013 05:02 AM

    asilva's Avatar

    I have the same problem, finally fixed by replacing AllowOverride none to AllowOverride All:

    <Directory />
    ## AllowOverride none
    ## Require all granted
         Options FollowSymLinks
         AllowOverride All
    </Directory>

  22. 22 Posted by Cain Velasquez on 27 Nov, 2014 07:26 PM

    Cain Velasquez's Avatar

    Hi,

    I was having issues when installing slim in godaddy (PHP 5.3)

    The htaccess wasn't working.
    I had to add the line

    RewriteBase /

    Things work now.
    Thanks to Andrew Smith

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]

  23. 23 Posted by Raja on 28 Mar, 2015 09:26 PM

    Raja's Avatar

    I have spent almost a day trying to figure this out and this example did the job, i thought i'd share it over here it might be helpful to someone...

    http://blog.mirohristov.com/web/hide-public-from-slim-or-mini2-framework-with-htaccess-and-bugfix/?fb_action_ids=414842255348437&fb_action_types=og.comments

  24. 24 Posted by Greg Elin on 16 May, 2015 06:04 AM

    Greg Elin's Avatar

    I found what I believe is an viable solution to have Slim run in a subdirectory of a larger site thanks to the observations at the top of this issue: https://github.com/slimphp/Slim/issues/521

    Turns out the easiest way to use Slim in a subdirectory is simply tack the path of the subdirectory into the mod_rewrite command and leave everything else alone, except prepending the path to any redirects within Slim.

    Here's an example set of directories under the site_root. In this case, I would be using Slim in a the "survey/music" directory only to coordinate a survey

    site_root
    + blog + survey/music + img -index.html - (other pages) + (other directories)

    The slim app, including slim's index.php, is inside "survey/music" directory.

    Add the directory path to your Slim path to the mod_rewrite for apache configuration. In my case, I added it the block in my virtual host definition file. Here is the snippet.

    RewriteEngine On 
    RewriteBase / 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^ survey/music/index.php [QSA,L]
    

    The web browser URL "http://mysite.com/survey/music/my/favs&quot; would correspond to the Slim route:

    $app->get('/my/favs', function () use ($app) {
      #your code
    });
    

    If you need to redirect you would have to redirect to the full path as seen by the browser,

    $app->redirect("/survey/music/my/favs");
    

    Finally, I had to juggle index.html and index.php with two routes:

    // ************
    $app->get('/index.html', function () use ($app) {
    
        $app->redirect("/survey/music/<something>/");
    
    });
    
    
    // ************
    $app->get('/', function () use ($app) {
    
        $app->redirect("index.html");
    
    });
    
  25. 25 Posted by Matteo Favaro on 21 Oct, 2015 07:53 AM

    Matteo Favaro's Avatar

    Hi to all i want to share my experience and how i solved:

    My directory structures:

    /var/www/                           (normal apache site position)
         site/ (the server's web root)
              [ANGULAR JS APPLICATION]
              index.html
         webserver/ (Slim application)
            .htaccess
            index.php
            [Other folder and libraries]
    

    The .htaccess content is:

    RewriteEngine On
    RewriteBase /webserver/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} (.*)/webserver/(.*)
    RewriteRule ^(.*)$ index.php [QSA]
    

    the site.conf for apache is :

    <VirtualHost *:80>
    DocumentRoot /var/www/site
    # Other directives here
    Alias "/webserver" /var/www/webserver
            <Directory /var/www/site>
                    Options Indexes FollowSymLinks MultiViews
                    AllowOverride All
                    Order allow,deny
                    allow from all
            </Directory>
    #only for logging purpose turn of in production
    LogLevel trace6 rewrite_module:trace6
    RewriteEngine On
           <Directory /var/www/webserver>
            DirectoryIndex index.php
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            php_admin_flag engine on
    #for mine special purpose
             php_admin_flag safe_mode on
            Order allow,deny
            allow from all
            </Directory>
    </VirtualHost>
    

    And all works:

    [rewrite:trace2] [pid 24102] mod_rewrite.c(468): - - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] init rewrite engine with requested uri /webserver/login
    [rewrite:trace1] [pid 24102] mod_rewrite.c(468): - - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] pass through /webserver/login
    [rewrite:trace3] [pid 24102] mod_rewrite.c(468): - - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] [perdir /var/www/webserver/] strip per-dir prefix: /var/www/webserver/login -> login
    [rewrite:trace3] [pid 24102] mod_rewrite.c(468):- - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] [perdir /var/www/webserver/] applying pattern '^(.*)$' to uri 'login'
    [rewrite:trace4] [pid 24102] mod_rewrite.c(468): - - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] [perdir /var/www/webserver/] RewriteCond: input='/var/www/webserver/login' pattern='!-f' => matched
    [rewrite:trace4] [pid 24102] mod_rewrite.c(468): - - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] [perdir /var/www/webserver/] RewriteCond: input='/webserver/login' pattern='(.*)/webserver/(.*)' => matched
    [rewrite:trace2] [pid 24102] mod_rewrite.c(468): - - [localhost/sid#7faa36ba53b8][rid#7faa36d9f1d0/initial] [perdir /var/www/webserver/] rewrite 'login' -> 'index.php'
    

    I suggest to use this useful link to test the htaccess rules:
    http://htaccess.madewithlove.be/

  26. 26 Posted by Alexander on 29 Feb, 2016 04:20 PM

    Alexander's Avatar

    Hi! I have a little problem with redirect and .htaccess

    my soft using directory /svod/...

    My directory structures:

    /www/test-site.com/svod/
    index.html (angular)
    scripts
    styles
    ....


    /www/test-site.com/svod/api <dir> libs -- Slim /www/test-site.com/svod/api/v1/ -- .htaccess -- config.php -- dbHelper.php -- index.php
    The .htaccess content is:
    RewriteEngine On
    RewriteBase /svod/api/v1/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    Now I look Error 500 in this page http://185.25.118.11/svod/#/app_views/idnt_clients
    in /svod/api/v1/index.php:

    <?php
    require BASE_PATH.'/svod/api/libs/Slim/Slim.php';
    require_once 'dbHelper.php';


    \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app = \Slim\Slim::getInstance(); $db = new dbHelper();
    Where I need fixed Error 500?
  27. 27 Posted by aman on 11 Mar, 2016 06:43 AM

    aman's Avatar

    PHP Seo Friendly URL but page error 404 in godaddy server

    .htaccess fill

    Options +FollowSymlinks
    Options -MultiViews

    RewriteEngine on
    RewriteBase /

    #rewritecond %{http_host} ^focusz.in [nc]
    #rewriterule ^(.*)$ http://www.focusz.in/$1 [r=301,nc]

    RewriteRule ^([a-zA-Z0-9_-]+)$ /index.php?a=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ /index.php?a=$1&b=$2
    RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ /index.php?a=$1&b=$2&c=$3
    RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ /index.php?a=$1&b=$2&c=$3&d=$4

    page error 404

  28. 28 Posted by highpointstudio... on 19 Mar, 2016 03:36 AM

    highpointstudios's Avatar

    I had the same problem - on OSX w/ Apache & php 5.6.19
    Fought this for more than a day.
    Turns out that the .htaccess file in the local web site directory was conflicting with the virtual hosts config file for apache2 (/private/etc/apache2/extra/httpd-vhosts.confg)

    So, I modified the vhosts config to have the following lines for 'localhost' and all is working fine.....

    <VirtualHost *:80>
            ServerName "localhost"
            DocumentRoot "/Users/username/Sites"

            <Directory /Users/username/Sites>
                    Allow From All
                    Options Indexes FollowSymLinks Multiviews
                    AllowOverride All
                    Order allow,deny
                    DirectoryIndex index.html index.php
                    php_admin_flag engine on
                    php_admin_flag safe_mode on
            </Directory>

            RewriteEngine On
    #These are in the local site .htaccess file
    # RewriteBase /
    # RewriteCond %{REQUEST_FILENAME} !-f
    # RewriteRule ^ index.php [QSA,L]

    </VirtualHost>

    ---------------------

    Then the .htaccess file in the root website folder has this (FYI: the public folder has all the app files):

    RewriteEngine On
    RewriteBase /RootWebSiteFolder/public/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [QSA,L]

  29. 29 Posted by propertyrudra12 on 20 Mar, 2016 07:43 AM

    propertyrudra12's Avatar

    I value the post.Really looking forward to read more. Much obliged.
    Hill Stations near Delhi @ http://hillstationsneardelhi.in

  30. 30 Posted by nawawori on 04 May, 2017 08:29 AM

    nawawori's Avatar

    This thing will work it again.
    http://themanifestmiracle.com/

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac