Redirect any GET request to a single PHP script

After many hours of working with .htaccess, I came to the end of sending any request to a single PHP script that would process:

  • Html generation (whether enabled or dynamic)
  • 301 Redirects with more logic flexibility (for dumb .htaccess-eer)
  • 404 errors if the request does not make sense.

leaving minimal functionality in .htaccess.

After some tests, this seems quite feasible and, from my point of view, more preferable. So much so that I wonder what is wrong or could go wrong with this approach?

  • Server performance
  • From the point of view of SEO, I see no problem, since the procedure will be "transparent" to the bots.

Redirector.php expects a query string consisting of the actual request. What will be the .htaccess code to send everything there?

+5
source share
2 answers

I prefer to move all your php files to another directory and put only 1 php file in your htdocs path, which handles all requests. Other files that you want to transfer without php, you can also place in this folder with this htaccess:

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

Existing files (jpg, js or ever) are still available without php. This is the most flexible way to implement this.

Example:

 - /scripts/ # Your PHP Files - /htdocs/index.php # HTTP reachable Path - /htdocs/images/test.jpg # reachable without PHP - /private_files/images/test.jpg # only reachable over a PHP  
+1
source

You can use this code to redirect all requests to a single file:

 RewriteEngine on RewriteRule ^.*?(\?.*)?$ myfile.php$1 

Please note that all requests (including stylesheets, images, ...) will also be redirected. Of course, there are other possibilities (rules), but this is the one I use, and it will contain the correct query string. If you do not need it, you can use

 RewriteEngine on RewriteRule ^.*?$ myfile.php 

This is a common technique, as bots and even users see only their URL, and not how it is processed internally. Server performance is not a problem at all.

Since you are redirecting all urls to a single php file, there is no longer a 404 page because it is cached by your .php file. Therefore, make sure that you handle incorrect URLs incorrectly.

+1
source

All Articles