Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache redirect all to index.php except for existing files and folders

I have index.php that reads full path by $_SERVER[‘REQUEST_URI’] variable. My task is when user enter: www.domain/resource/777 redirect to index.php with path /resource/777 and parse $_SERVER[‘REQUEST_URI’] to do some logic. But I have also real files and folders like:

  • css/theme.css
  • assets/assets.js
  • resource/locale.js

When I try this config:

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

Client could not get all css and etc files. How to write correct rule in Apache to achive this?

like image 660
Eazy Avatar asked Dec 08 '15 06:12

Eazy


3 Answers

If you are using Apache 2.2.16 or later, you can replace rewrite rules entirely with one single directive:

FallbackResource /index.php

See https://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresource

Basically, if a request were to cause an error 404, the fallback resource uri will be used to handle the request instead, correctly populating the $_SERVER[‘REQUEST_URI’] variable.

like image 71
SirDarius Avatar answered Nov 17 '22 20:11

SirDarius


Your rule is fine. Issue with css/js/image is that you're using relative path to include them.

You can add this just below <head> section 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.

Also keep just this rule in your .htaccess:

DirectoryIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^[^.]+$ index.php [L]
like image 43
anubhava Avatar answered Nov 17 '22 20:11

anubhava


According to the documentation REQUEST_FILENAME only evaluates to the full local filesystem path to the file if the path has already been determined by the server.

In a nutshell this means the condition will work if it is inside an .htaccess file or within a <Directory> section in your httpd.conf but not if it's just inside a <VirtualHost>. In this latter case, you can simply wrap it in a <Directory> tag to get it working.

<VirtualHost *:80>
     # ... some other config ...
    <Directory /path/to/your/site>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ /index.php [L]
    </Directory>
</VirtualHost>
like image 1
Matt Raines Avatar answered Nov 17 '22 19:11

Matt Raines