URL handling – PHP vs Apache Rewrite

后端 未结 4 1221
[愿得一人]
[愿得一人] 2021-01-29 09:15

Currently I let a single PHP script handle all incoming URLs. This PHP script then parses the URL and loads the specific handler for that URL. Like this:

if(URI          


        
相关标签:
4条回答
  • 2021-01-29 09:46

    The PHP approach is correct but it could use a bit of improvement.

    $file = $uri.".php";
    if (!is_file($file)) { header("Status: 404 Not Found"); require_once(404.php); die(); }
    require_once($uri.".php");
    
    0 讨论(0)
  • 2021-01-29 09:58
    RewriteRule ^([a-z]+)$ $1.php [L]
    

    and rename root.php to index.php.

    0 讨论(0)
  • 2021-01-29 10:03

    OK, as for efficiency - htaccess version with regexp and php version with single regexp and loading of matching file would be faster than many htaccess rules or many php if - else

    Apart from that, htaccess and php way should be similar in efficiency in that case, probably with little gain with htaccess (eliminating one require in php)

    0 讨论(0)
  • 2021-01-29 10:11

    So, here's my question: What option is better (efficiency-wise and otherwise) and why?

    If every resource has to run through a PHP based check, as you say in your comment:

    some resources are only available to logged in users, so I get to check cookies and login state first, then I serve them with readfile().

    then you can indeed use PHP-side logic to handle things: A PHP instance is going to be started anyway, which renders the performance improvement of parsing URLs in Apache largely moot.

    If you have static resources that do not need any session or other PHP-side check, you should absolutely handle the routing in the .htaccess file if possible, because you avoid starting a separate PHP process for every resource. But in your case, that won't apply.

    Some ideas to increase performance:

    • consider whether really every resource needs to be protected through PHP-based authentication. Can style sheets or some images not be public, saving the performance-intensive PHP process?

    • try minifying resources into as few files as possible, e.g. by minifying all style sheets into one, and using CSS sprites to reduce the number of images.

    • I've heard that nginx is better prepared to handle this specific kind of scenario - at least I'm told it can very efficiently handle the delivery of a file after the authentication check has been done, instead of having to rely on PHP's readfile().

    0 讨论(0)
提交回复
热议问题