【问题标题】:Apache, how to handle unknown php file like standard URLs?Apache,如何处理未知的 php 文件,如标准 URL?
【发布时间】:2020-05-12 05:50:35
【问题描述】:

我有一个 Symfony 网站,我在其中重命名了主入口点,因此“index.php”无法访问,也无法被搜索引擎索引。它运作良好。但是,当我尝试访问此文件时,我得到一个 404 文件未找到,此 404 页面由 Apache 而不是由应用程序处理,它是标准的 404 页面:

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

我希望 Symfony 应用程序处理像 /index.php(实际上是 *.php)这样的 URL,以显示具有良好布局的自定义错误页面。我的虚拟主机看起来像这样,我尝试添加“目录索引”指令但没有成功。

# 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>

【问题讨论】:

    标签: php apache symfony vhosts


    【解决方案1】:

    这可以用mod_rewrite完成,回复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]
    

    默认错误文档可用于将错误代码分派给 PHP:

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

    然后仍然可以发送任何想要的header() - 或者只显示具有相同标题的页面。

    【讨论】:

    • 您好,感谢您的回答。抱歉耽搁了,我会尽快检查。 ErrorDocument 似乎是一个不错的选择。 :)
    • 您好,效果很好。我不得不把它放在.htaccess 文件中。现在重定向到我的新隐藏前端控制器(我在最后替换了RewriteRule . /index.php [L]),然后应用程序手动重定向到好页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2016-04-28
    相关资源
    最近更新 更多