Hosting Symfony5 in Shared Host sub direrctory to hide /public in URL

Hosting Symfony in Shared host sub dir like www.domain.com/project etc

Pranan Subba
2 min readJun 2, 2021

Hosting Symfony in Shared Host in sub dir or folder is pain in the butt. Recently I had to host Symfony project where the client had asked me to host Symfony 5 project inside a folder so that the user can access as domain.com/project etc and no subdomain. Although I had few experience Hosting Symfony application direct in public_html but I never done in public_html/folder.

Say your dir looked like this and you don’t want /public in URL but want your subdir name

public_html
other_project
project
bin
...
...
public
etc etc

My first problem was to hide /public from URL so that I can access the url as

domain.com/project not domain.com/project/public

I tried all my best to ask for help to developers, posted couple of Question in Stackoverflow ,but didn’t worked. So finally used a Laravel technique to conquer this challage with some hacks.

Since we know, esp Symfony Developer, there is no such as .htaccess and server.php in root, but I did with that two files.

I put the following .htaccess in project folder i.e., public_html/project

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php

and Server.php as well

<?php/**
* Laravel — A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH)
);
// This file allows us to emulate Apache’s “mod_rewrite” functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a “real” web server software here.
if ($uri !== ‘/’ && file_exists(__DIR__.’/public’.$uri)) {
return false;
}
require_once __DIR__.’/public/index.php’;

NOTE: The codes are found in Laravel Docs

Now after doing this there was a problem in routes: say, suppose if I click on homepage route e.g. domain.com/project I was redirected to parent domain that is in domain.com. First I tried adding in Controller in Twig ,but no use.

Then I used the following method in twig:

I added subdir name in all the routes in twig: eg.

<a href=”/project”>Home</a>
<a href=”/project/Contact”>Contact</a>

And it worked successfully also don’t forget to add ‘/’ before folder name else it will add after the domain like: domain.com/project/project/xyz

NOTE: I tried in free hosting platform 000webhost it didn’t worked and also I didn’t tried much.

And don’t forget to clear cache while doing…

Cheers!!

--

--

Pranan Subba
Pranan Subba

Written by Pranan Subba

0 Followers

<?php echo “Hello World!”; ?>

No responses yet