Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache, how to handle unknown php file like standard URLs?

I am have a Symfony website where I have renamed the main entry point so "index.php" can't accessed nor being indexed by search motors. It works well. But, when I try to access this file I get a 404 file not found, this 404 page is handled by Apache and not by the application, it's the standard 404 page:

Not Found
The requested URL was not found on this server.

I'd like URLs like /index.php (*.php in fact) to be handled by the Symfony application to display the customised error page with the good layout. My vhost look like this, I tried to add a "directory index" directive but without success.

# configuration/vhosts/prod/mywebsite.com-le-ssl.conf
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName www.mywebsite.com
        DocumentRoot /var/www-protected/mywebsite.com/public

        <Directory /var/www-protected/mywebsite.com/public>
            AllowOverride All
            Require all granted
            FallbackResource /my-secret-entry-point.php
        </Directory>

        RedirectMatch 404 /\.git

        ErrorLog /var/log/apache2/mywebsite.com_error.log
        CustomLog /var/log/apache2/mywebsite.com_access.log combined

        RewriteEngine on
        RewriteCond %{SERVER_NAME} =mywebsite.com
        RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

        SSLCertificateFile /etc/letsencrypt/live/www.mywebsite.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/www.mywebsite.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </VirtualHost>
</IfModule>
like image 581
COil Avatar asked Jan 26 '20 18:01

COil


1 Answers

This can be done with mod_rewrite, replying with 301:

Options +FollowSymLinks
DirectoryIndex index.php

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^.*/index\.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Default error documents can be used to dispatch the error-codes to PHP:

ErrorDocument 404 https://mywebsite.com/error/page/404
ErrorDocument 500 https://mywebsite.com/error/page/500

Then one still can send whatever header() one wants - or just show a page with the same headers.

like image 183
Martin Zeitler Avatar answered Nov 09 '22 06:11

Martin Zeitler