Search code examples
.htaccess

.htaccess > redirect all subfolders to root (ignore trailing slash)


My gosh - I hate .htaccess ... and don't understand how the hell anything is working. I am trying to ignore 'subfolders' and use these as guest identifyer. Ex:

User types > http://subdomain.domain.com/guest_id

Server sends > http://subdomain.domain.com/index.php

Browser shows > http://subdomain.domain.com/guest_id

My htaccess file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php [NC]

The code works great... unless there is a trailing slash. In this case, all files are served as 'index.php'. The main Index.php is showing properly, but all external scripts / css / etc. are served as /guest_id/index.php (thus... do not load).

FYI, there might be a conflict as my 'subdomain' is actually invisibly serving domain.com/event/

I have been trying so many permutations... without really understanding how htaccess work.

Your help will be sooooo much appreciated. 1,000 thanks in advance! Damien


Solution

  • When you have URL such as http://subdomain.domain.com/guest_id/ and are using relative links for your css/js/images then browser attempts to resolve all links by prefixing them with current path hence src='image.png' is resolved as http://subdomain.domain.com/guest_id/image.png instead of http://subdomain.domain.com/image.png.

    You can have a rule to force remove trailing slash at the end of all non-directory URLs.

    RewriteEngine On
    
    # Unless directory, remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^(.+)/+$
    RewriteRule ^ %1 [R=301,NE,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
    

    Also you can add this just below <head> tag of your page's HTML:

    <base href="/" />
    

    so that every relative URL is resolved from that base URL and not from the current page's URL.