Apache redirects everything to index.php except existing files and folders

I have index.php that reads the full path of the variable $_SERVER['REQUEST_URI'] . My task is when the user enters: www.domain/resource/777 redirect to index.php using the path /resource/777 and parse $_SERVER['REQUEST_URI'] to execute some logic. But I also have real files and folders, for example:

  • CSS / theme.css
  • assets /assets.js
  • Resource /locale.js

When I try this configuration:

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

The client could not get all the css and etc. files How to write the correct rule in Apache to achieve this?

+8
php apache .htaccess
source share
5 answers

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

 FallbackResource /index.php 

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

Basically, if the request was to cause a 404 error, instead, the backup resource uri will be used instead, correctly populating the variable $_SERVER['REQUEST_URI'] .

+5
source share

According to the REQUEST_FILENAME documentation, it evaluates only the full path to the local file system to the file if the path is already defined by the server.

In a nutshell, this means that the condition will work if it is inside the .htaccess file or in the <Directory> section of your httpd.conf, but not that it is inside the <VirtualHost> . In this latter case, you can simply wrap it with a <Directory> tag to make it work.

 <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> 
+2
source share

Your rule is fine. The problem with css / js / image is that you are using a relative path to include them.

You can add this just below the <head> in the HTML page:

 <base href="/" /> 

so that each relative URL is removed from this base URL, and not from the current page URL.

Also keep only this rule in your .htaccess:

 DirectoryIndex index.php RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^[^.]+$ index.php [L] 
+1
source share

You can install the document with an error in your htaccess file to use index.php, then a non-existing file is requested:

 ErrorDocument 404 /index.php 
0
source share

So far, only this has helped me:

 RewriteEngine On RewriteCond %{REQUEST_URI} !^/src/ RewriteCond %{REQUEST_URI} !^/assets/ RewriteCond %{REQUEST_URI} !^/resource/ RewriteCond %{REQUEST_URI} !^/data.json RewriteRule ^(.*)$ /index.php [L] 
0
source share

All Articles