Search code examples
apache.htaccessmod-rewriteroutesurl-rewriting

Rewrite root to subfolder (.htaccess) except some directories


I have the following folder structure:

  • app/ (contains index.php, js/, public/)
  • v1/
  • .htaccess

Requests to v1 should work as usual. All other requests should go to /app without changing the URL

www.xxx.com/           (displays: app/index.php)
www.xxx.com/v1         (displays: v1/index.php)
www.xxx.com/js/xxx.js  (displays: app/js/xxx.js)

Is this possible?

Basically, static folders: v1, app/js (without app), app/public (without app)

All other requests go to app/index.php without URL changes.


Solution

  • You may use this rule in site root .htaccess:

    RewriteEngine On
    
    # landing page
    RewriteRule ^/?$ app/index.php [L]
    
    # if v1/file exists then use it
    RewriteCond %{DOCUMENT_ROOT}/v1/$1 -f
    RewriteRule .+ v1/$0 [L]
    
    # if app/public/file exists then use it
    RewriteCond %{DOCUMENT_ROOT}/app/public/$1 -f
    RewriteRule .+ app/public/$0 [L]
    
    # if app/js/file exists then use it
    RewriteCond %{DOCUMENT_ROOT}/app/js/$1 -f
    RewriteRule .+ app/js/$0 [L]
    
    # if not a file, not a dir and not starting with v1    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule !^v1/ app/index.php [L,NC]