Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache 2.4 + PHP-FPM, catching error pages

Tags:

php

apache

Here is my vhost file:

 <VirtualHost *:80>
   ServerName awesome.dev

   ## Vhost docroot
   DocumentRoot "/var/www/awesome"

   ## Directories, there should at least be a declaration for /var/www/awesome
   <Directory "/var/www/awesome">
     Options Indexes FollowSymLinks MultiViews
     DirectoryIndex index.php
     AllowOverride All
     Require all granted
   </Directory>

   ## Logging
   ErrorLog "/var/log/apache2/w0JhArMoDehc_error.log"
   ServerSignature Off
   CustomLog "/var/log/apache2/w0JhArMoDehc_access.log" combined

   ## Server aliases
   ServerAlias www.awesome.dev

   ## SetEnv/SetEnvIf for environment variables
   SetEnv APP_ENV dev

   ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/awesome/$1
 </VirtualHost>

I'm trying to catch all requests for non-existing *.php files.

For example, if /var/www/awesome/index.php exists and I go to http://foo.com/index.php I get the correct response, but if /var/www/awesome/foo.php does not exist and I go to http://foo.com/foo.php, I am simply getting a response of File not found..

The .htaccess file isn't being read because Apache hands everything off to PHP-FPM.

I need to catch all 404 requests and show a common error page, as you would normally see on any site.

However, since Apache hands everything off to php-fpm, it doesn't seem to be handling these errors properly.

like image 440
Juan Treminio Avatar asked Sep 12 '14 06:09

Juan Treminio


2 Answers

I used to have the same problem and finally I fixed it.

Try add this after ProxyPassMatch setting:

ProxyErrorOverride on

BTW, do not forget your

ErrorDocument 404 /path/to/file

setting.

like image 121
Shiqi Zhong Avatar answered Nov 01 '22 01:11

Shiqi Zhong


For anyone reading today, HERE is the correct answer, thanks to Tito1337 for his answer.

ProxyErrorOverride may give you problems or break your application if you set 404's or handle some errors elsewhere in your code, and is more complicated to implement.

Instead, you should pass the request to php-fpm only if the file exists. If the file does not exist, Apache will direct to your defined ErrorDocument. You can add this check around your PHP handler in the Apache config.

Example for CentOS 8:

#
# Redirect to local php-fpm (no mod_php in default configuration)
#
<IfModule !mod_php5.c>
  <IfModule !mod_php7.c>
    # Enable http authorization headers
    SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1

    <FilesMatch \.(php|phar)$>
        
        # NEW ADDITION - CHECK IF FILE EXISTS FIRST
        <If "-f %{REQUEST_FILENAME}">
            
            SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"
            
        </If>
        
    </FilesMatch>
  </IfModule>
</IfModule>
like image 22
Dan Avatar answered Nov 01 '22 02:11

Dan