skip to Main Content

After many hours messing with .htaccess I’ve arrived to the conclusion of sending any request to a single PHP script that would handle:

  • Generation of html (whatever the way, includes or dynamic)
  • 301 Redirections with a lot more flexibility in the logic (for a dumb .htaccess-eer)
  • 404 errors finally if the request makes no sense.

leaving in .htaccess the minimal functionality.

After some tests it seems quite feasible and from my point of view more preferable. So much that I wonder what’s wrong or can go wrong with this approach?

  • Server performance?
  • In terms of SEO I don’t see any issue as the procedure would be “transparent” to the bots.

The redirector.php would expect a query string consisting on the actual request.
What would be the .htaccess code to send everything there?

2

Answers


  1. You can use this code to redirect all requests to one file:

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

    Note that all requests (including stylesheets, images, …) will be redirected as well. There are of course other possibilities (rules), but this is the one I am using and it will keep the query string correct. If you don’t need it you can use

    RewriteEngine on
    RewriteRule ^.*?$ myfile.php
    

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

    Because you redirect all URLs to one php file there is no 404 page anymore, because it gets cached by your .php file. So make sure you handle invalid URLs correctly.

    Login or Signup to reply.
  2. I prefere to move all your php files in a other directory and put only 1 php file in your htdocs path, which handle all requests. Other files, which you want to pass without php, you can place in that folder too with this htaccess:

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

    Existing Files (JPGs,JS or what ever) are still reachable without PHP. Thats the most flexible way to realize it.

    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 script
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search