Search code examples
php.htaccesssymfonyherokusymfony5

How redirect to a static page in Public dir in a Symfony5 project


I have a simple static website. On that I build a Symfony project to have an admin panel with easyadmin-bundle and an API to retreive data with ajax on the static page.

The project structure is like this:

  • bin/
  • config/
  • migrations/
  • public/
    • css/
    • js/
    • index.html
    • index.php
    • .htaccess
  • src/
  • templates/

Everythings works fine but I can only access to the page when I call : myfakedomain.com/index.html
The page myfakedomain.com is returning a 404 error What I would like to have is an automatic redirection from myfakedomain.com/ to myfakedomain.com/index.html

I think this can be done ine the .htaccess file. This is the current content of the .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$
    RewriteRule .* - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by Apache
    RewriteCond %{HTTP:Authorization} .+
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]

    RewriteCond %{ENV:REDIRECT_STATUS} =""
    RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>

This project is deployed on heroku so I create a Procfile

web: vendor/bin/heroku-php-apache2 public/

May it come from that ?


Solution

  • It comes from your .htacess which redirects all requests to index.php.

    Option1 - using Apache (I don't like this method because of side effects)

    • Exclude the existing files from the redirection.
    • Declare index.html as the default file instead of index.php (when calling .
    • Tips: apache-pack can help you. It contains an up-to-date default configuration

    Option2 - using Symfony (Recommanded way):

    • move index.html to template/index.html
    • Create a controller returning a response rendering the template files
    # src/Controller/HomeController.php
    class HomeController extends AbstractController
    {
        #[Route(name:'home', '/')]
        public function index (): Response 
        {
            return $this->render('index.html');
        }
    }