Symfony 2 project in nested directory - php

I need to deploy a Symfony 2 project in nested directory on production server. Effectively, this would mean that all URLs are prefixed with /subdirectory/ path, i.e.
http://host.com/subdirectory/project/web/app.php/survey
I don't need URL rewriting and are am not going to set it up. The app should work when accessed via above URL only.
The problem I have is that all links generated by path and asset Twig functions are relative to server root (/), and not subdirectory the project is in (/subdirectory/). Is there any config parameter in Symfony 2 to override relative paths globally?
I tried to work around that problem by adding HTML tag, but it doesn't work for links.
Update: I owe you further details. I'm running IIS with its version of mod_rewrite, so part of your suggestions may still be valid.
Update: Ideally I would like to see a solution that sets root dir on AppKernel object - method AppKernel::setRootDir() had it existed to complement existing AppKernel::getRootDir().

Strange... with default config, path/asset should handle subdirectories. Have you tried it with symfony distribution out-of-the-box? On localhost im mostly using it this way.
Would you mind posting your config file?
Anyway...
For assets paths you could try to configure:
#config.yml
templating:
assets_base_urls: { http: "http://yoursite.com/dir1", ssl: "https://yoursite.com/dir1" }
(http://symfony.com/doc/current/reference/configuration/framework.html#assets-base-urls)
For router you should read: http://symfony.com/doc/current/cookbook/console/sending_emails.html#configuring-the-request-context-globally
It could give you some ideas about changing router context like:
# app/config/parameters.yml
parameters:
router.request_context.host: example.org
router.request_context.scheme: http
router.request_context.base_url: my/path
Anyway - context is automaticlly set based on request information. Try to debug:
$context = $this->getContainer()->get('router')->getContext();
// you should be mainly interested in:
$context->getBaseUrl();
It is possible to easily create listener class which will manually set your base url if anyhow it is wrong:
class RouterContextListener {
protected $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onKernelRequest(Event $event)
{
$this->router->setBaseUrl('somedir');
}
}

You are looking for RewriteBase rule, add it to your in your .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /subdirectory/project/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>
Also take a look onto symfony-standard 2.3 .htaccess file, mb it can help
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]
# Rewrite all other queries to the front controller.
RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>

Look at app/config/routing.yml where you import routing from your bundles. Records in that file would look similar to this:
somename:
resource: "#YourBundle/Resources/config/routing.yml"
prefix: /
You can add your subdirectory in prefix, like prefix: /subdirectory
Then all generated URLs will include subdirectory.

To enable it the rewrite module, run "apache2 enable module rewrite":
sudo a2enmod rewrite
You need to restart the webserver to apply the changes:
sudo service apache2 restart
VirtualHost should be like this
ServerName localhost.myproject.dev
ServerAdmin webmaster#localhost
DocumentRoot /var/www/project_path
<Directory /var/www/project_path>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /app.php [QSA,L]
</IfModule>
</Directory>
this option is redirect your index.php, index.html or whatever:
Options Indexes FollowSymLinks MultiViews
it will rewrite your htacces!
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /app.php [QSA,L]
</IfModule>

My solution to this on a local environment was adding the following code in app/config/config.yml
framework:
assets:
base_urls:
- 'http://localhost/symfony_dir/'
No rewrite needed!

Related

Apache rewrite rules for running a Symfony application in a sub-directory when rewrite rules already exist for legacy application

Version Information: Apache v2.4.18 on Ubuntu, PHP version 7.1,Symfony v3.2
I've been trying to get this working for a couple of days now and keep hitting problems, I have an existing PHP application using a custom built framework with the following Apache VirtualHost configuration:
<VirtualHost *:80>
ServerName dvlp.mydomain.com
DocumentRoot /var/www/my-site/com
RewriteEngine On
# Do nothing for the Home page ('^/$'), specific directories, static files.
RewriteRule ^/(?:$|shared|asset)|\.(?:php|ico|txt|xml) - [L]
# Search engine friendly request URIs (most, but not all, without a query string).
RewriteRule ^/([a-z0-9-]+/?)$ /index.php?param1=$1 [L,QSA]
RewriteRule ^/([a-z0-9-]+)/([a-z0-9-\.]+/?)$ /index.php?param1=$1&param2=$2 [L,QSA]
RewriteRule ^/([a-z0-9-]+)/([a-z0-9-]+)/(.+)$ /index.php?param1=$1&param2=$2&param3=$3 [QSA]
<Directory />
Options FollowSymLinks
AllowOverride None
ErrorDocument 404 /404.php
</Directory>
</VirtualHost>
What I am trying to do is install a Symfony application to work within a sub-directory. I've created my Symfony application in /var/www/symfony-app and created a symbolic link /var/www/my-site/com/my-symfony which points to /var/www/symfony-app/web.
I then tried the following on line 6 of my VirtualHost file:
RewriteRule ^/(?:$|my-symfony|shared|asset)|\.(?:php|ico|txt|xml) - [L]
Visiting dvlp.mydomain.com/my-symfony in the browser takes me to the directory listings for the /var/www/symfony-app/web folder. I tried adding an index.php file to /var/www/symfony-app/web which simply includes app_dev.php and it loaded the home page, but I I tried visiting dvlp.mydomain.com/my-symfony/edit-personal-details I get the 404 error page from my existing application.
I realised now that I need separate rewrite rules for this sub-directory, for Symfony this is usually written as the following:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
So I undid the change I made to line 6 of the VirtualHost file and added a new line as follows:
RewriteRule ^/my-symfony(.*)$ /my-symfony/index.php [L,QSA]
This results in a 404 error:
No route found for "GET /my-symfony/" (from "http://dvlp.mydomain.com/")
And if I try visiting dvlp.mydomain.com/my-symfony/edit-personal-details I get the same 404 error:
No route found for "GET /my-symfony/edit-personal-details" (from "http://dvlp.mydomain.com/")
The last thing I have tried is adding a prefix to my Symfony routing.yml:
my_symfony:
resource: "#MySymfonyBundle/Controller/"
type: annotation
prefix: /my-symfony
This then loads the pages correctly but with no images or stylesheets because they are trying to load from the DocumentRoot (e.g dvlp.mydomain.com/css instead of dvlp.mydomain.com/my-symfony/css).
I would appreciate any input as to where I am going wrong. Thanks.
I finally managed to get this working as intended by adding a "Location" tag containing specific RewriteRules and a RewriteBase for the Symbolic link. For information, final VirtualHost config below:
<VirtualHost *:80>
ServerName dvlp.my-domain.com
DocumentRoot /var/www/my-site/com
RewriteEngine On
<Location /my-symfony>
RewriteBase /my-symfony
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app_dev.php [QSA,L]
</Location>
# Do nothing for the Home page ('^/$'), specific directories, static files.
RewriteRule ^/(?:$|my-symfony|shared|asset)|\.(?:php|ico|txt|xml) - [L]
# Search engine friendly request URIs (most, but not all, without a query string).
RewriteRule ^/([a-z0-9-]+/?)$ /index.php?param1=$1 [L,QSA]
RewriteRule ^/([a-z0-9-]+)/([a-z0-9-\.]+/?)$ /index.php?param1=$1&param2=$2 [L,QSA]
RewriteRule ^/([a-z0-9-]+)/([a-z0-9-]+)/(.+)$ /index.php?param1=$1&param2=$2&param3=$3 [QSA]
<Directory />
Options FollowSymLinks
AllowOverride None
ErrorDocument 404 /404.php
</Directory>
</VirtualHost>

Laravel routes not working except for root

I have been spending hours on this issue and hope to find my way out. I have set up laravel correctly, created a project myapp
My route.php file just contains
Route::get('/', function()
{
return View::make('hello');
});
Route::get('/users', function()
{
return 'Users!';
});
When I run
http://localhost/myapp/public/
I get the laravel start page correctly
When I run
http://localhost/myapp/public/users
I get
The requested URL /myapp/index.php was not found on this server.
I don't know why its looking for index.php.
When I run
http://localhost/myapp/public/index.php/users
I get a page with text "Users". I should obtain this page when running
http://localhost/myapp/public/users
instead.
Below is my .htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
Rewritebase /myapp/
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Any ideas? Am running a Apache on Linux.
Your RewriteBase is set to /myapp/ but your index.php file is in /mayapp/public/ is it not?
As such, I think you'll find the RewriteBase needs to be /myapp/public/.
Make sure you have mod_rewrite enabled on apache web server.
Make sure that your vhost config allows and parses htaccess files
Just do this and try to restart the apache.
sudo a2enmod rewrite
To restart apache: sudo services apache2 restart
I ran into same problem with production server, nothing seemed to work, no chmod/s no other solution but adding a simple line to .htaccess worked.
RewriteBase /
Thanks to the thread and user odaria
In your application/config/application.php file change:
'index' => 'index.php',
to:
'index' => '',
That should tell laravel not to use index.php and to rewrite correctly.
It works with standard .htaccess file which comes with laravel (haven't checked if you modified it)
Use this re-write rule:
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /my_app
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Also, in `application/config/app.php' change:
'index' => 'index.php'
to
'index' => ''
The quickest way is to add a symbolic link in command line:
ln -s your/acutal/path/myapp/public app-dev
Now browse http://localhost/app-dev should work fine as well as all the routes. You can change app-dev to whatever you want as the name.

Apache htaccess mod rewrite redirection using Controller GET variables in PHP index page

I am working with a custom MVC PHP framework and the index page (acting as a router) receives a GET variable "do" which contains the path that it will route to. If this variable is not set, it defaults to the Auth controller, method login.
require_once('config.php');
$controllerAction = isset($_GET['do'])?$_GET['do']:"auth/login";
require_once('core/main.php');
Then the index page (source code above) passes this $controllerAction to the main.php file, which autoloads the main controller and then loads the requested controller.
Thus, the URIs in this framework are of the form mysite.com/?do=controller/method/variable and I need it to be in the form mysite.com/controller/method/variable.
Here is the .htaccess file I tried to use, it just didn't work (I have other htaccess files working on the same server so it's not an Apache problem) :(
RewriteEngine On
RewriteRule ^([^/]*)$ /?do=$1 [L]
Someone suggested that I can do this using PHP but I am not sure how to go about that.
Edit:
The error is that I get "This page cannot be displayed", 404 errors, whenever I try to directly access the mysite.com/controller/method links rather than the default mysite.com?do=controller/method
Further Edit
(please note that other virtual hosts work fine on my localhost):
(XAMPP) Apache Virtual Hosting Info:
<VirtualHost *:80>
DocumentRoot "D:\sites\mysite.com\root\wwwroot"
ServerName mysite.com
ServerAlias mysite.com
<Directory "D:\sites\mysite.com\root\wwwroot">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
File structure (Windows):
D:\
--sites
----mysite.com
--------#client_details
--------root
-----------#devfiles
-----------#vars_pwd
-----------wwwroot
--------------config
--------------core
--------------application
------------------controllers
------------------libraries
------------------models
------------------views
----------------------css
----------------------javascript
----------------------images
----------------------icons
First of all, there are some issues with your .htaccess contents. It's always a good idea to not rewrite if a file with the requested name exists. This allows you to have an img/ folder for your images or any other static content like css files, javascript, downloads, etc.. The first RewriteCond tells Apache to only rewrite if no folder with this name exists. The second one does the same with files. Then you probably want the QSA (i.e. Query String Append) option, which will pass all other GET variables to your script.
Under this conditions you can simplify the regex and use this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?do=$1 [L,QSA]
You might be surprised because this is more or less the same as others posted. I use similar things for many of my projects and I've just tested it, I can guarantee that it works. There must be something wrong with your apache config.
When you have problems with mod_rewrite, the first thing you should try is to enable the module itself. Type these commands as root in your shell:
a2enmod rewrite
/etc/init.d/apache2 restart
The first one activates the module (or complains with Module rewrite already enabled if everything is ok) and the second one restarts your Apache server. The path may of course be different on your server.
Then you have to make sure that your VHost config allows you to use .htaccess files and do rewrites. This means AllowOverride must be set to at least FileInfo (or All). You could also try to put the rewrite rules right into the config file. Your config should look similar to this:
<VirtualHost *:*>
ServerName test.example.com
ServerAlias www.test.example.com
DocumentRoot /home/sites/test/
<Directory "/home/sites/test/">
Allow from all
AllowOverride All
Options +Indexes
</Directory>
</VirtualHost>
Note that you have to restart Apache if you change anything in there.
If that all doesn't help, it's always a good idea to have a look at the error logs. On my system they're located at /var/log/apache2/error.log (debian). They might give you more information on what's going wrong.
Try
RewriteEngine On
RewriteRule ^([^/]*)$ index.php?do=$1 [L]
Try
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?do=$1 [L]
Check your apache logs, access logs specifically. If the folder is present in the web root, then you should be able to access it directly :). You might also want to check if you have duplicate virtualhost entries for the same site by chance.
This one is my customized MVC framework which is based on cake
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?do=$1 [QSA,L]
</IfModule>
May be this should help. The typical URL pattern for this site.com/controller/method
I don't know what your domain setup is like, but here are some suggestions.
If your code resides in the root of your folder, and the index file is called index.php try the following:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?do=$1 [L,QSA]
If your website exists in a subfolder e.g. www.example.com/site/, and the index file is index.php Then try the following (change /site/ to whatever your folder is).
RewriteEngine On
RewriteBase /site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /site/index.php?do=$1 [L,QSA]
If you still get the 404 error message then do the following:
Make sure your site allows .htaccess files to be processed by checking AllowOverride is set to all. If you don't have access to the necessary config files to check, a simple test is to setup an .htaccess rule to redirect to a dummy file on your system. If it works, then your .htaccess is being executed fine.
Have a look at your MVC framework to see what page it's actually sending the request to. The problem may be that you haven't defined a handler for that particular request, and the default action of your MVC framework is to throw a 404 error.
Edit: Just reading your description, I notice you said that the URL should basically be something like mysite.com/?do=controller/method/variable. If it has be very strict about this format, then you'll also need to put in rules for removing any leading or trailing slashes, e.g. the following re-write rule should do it:
RewriteRule ^\?(.*)\?$ /index.php?do=$1 [L,QSA]
(This makes the leading and trailing slashes optional, but it should remove them from the actual value you pass to do).

zend site needs alias too

I have a zend site where DocRoot is set to public/ and URL as
(http://dothat.com/controllerA/action9/) - which is working properly.
I also need to run a copy of that site on the same server as
(http://dothat.com/now/controllerA/action9/) running on same folder.
(The urls given are examples)
Please suggest on how can this be done without spoiling zend setup itself.
I would personally just do a simple Zend route in your Bootstrap.
Example:
protected function _initRoutes()
{
$this->bootstrap('frontController');
$frontController = Zend_Controller_Front::getInstance();
$nowRoute = new Zend_Controller_Router_Route("now/:controller/:action");
$frontController->getRouter()->addRoute("now", $nowRoute);
}
Routes in Zend are very powerful and fun to setup. I actually have mine in an outside .ini file to make it easier to setup, even environment aware.
it's working for me
/etc/httpd/conf.d/zendproject.conf
Alias /zendproject/ /var/www/vhosts/zendproject/public/
<Directory "/var/www/vhosts/zendproject/public/">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from All
</Directory>
public/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ /zendproject/index.php [NC,L]
How about that idea:
An alias in Apache (if it's the http server you're using)
Alias /now /path/to/zend/public
<Directory /path/to/zend/public>
SetEnv APPLICATION_ENV development
...
</Directory>
And you have to care for the .htacces too
...
RewriteRule ^.*$ /now/index.php [NC,L]
E.g. with another environmental variable for the path in the rewrite rule..

CodeIgniter configuration with mod_rewrite, xampp and windows

I'm a noob to CodeIgniter and am trying to figure out the configuration for an app I'm building. Something is wrong with my setup.
I'm running XAMPP on Windows and am using an alias directory to point to the applications directory. In other words: "http://localhost/app_name/ " points to the root directory of the application. It all seems to work well until I do the .htaccess for mod_rewrite. Then every time I try to go to a controller I get pitched back to the xampp root.
My config is:
Directories
/app_root
/app_root/codeigniter // where code igniter is located.
/app_root/main // where the main app is located. It' the applications
// directory cut from code igniter and renamed.
.htaccess
<IfModule mod_rewrite.**so**>
RewriteEngine On
RewriteBase **/app_name/**
RewriteCond %{REQUEST_URI} ^codeigniter.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
index.php
$system_folder = "#codeigniter";
$application_folder = "main";
app_name/main/config/config.php
$config['base_url'] = "http://localhost/app_name/";
$config['index_page'] = "";
app_name/main/config/routes.php
$route['default_controller'] = "welcome";
I should also state that the app_name directory is an alias for a different drive than the apache root.
Apache Root: c:\xampp\htdocs\
App_name: d:\projects\app_name\development\
The alias is:
Alias /app_name "d:/projects/app name/development"
<Directory "d:/projects/app name/development">
Options Indexes FollowSymLinks ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Thanks in advance for the help... And if you don't mind please "explain" what you're doing when you answer with code. I want to know what I'm doing wrong. If you can help me with this I'll buy you a beer (via PayPal). This is frustrating.
Success!!
I finally managed to get URL rewrite working and what a long arduous journey it was. Here is what I got working finally. Take note that there is no backslash on the RewriteBase. Very interesting given what I've read. Thanks to everybody who tried to help.
# Options
Options -Multiviews
Options +FollowSymLinks
#Enable mod rewrite
RewriteEngine On
#the location of the root of your site
#if writing for subdirectories, you would enter /subdirectory
RewriteBase /app_name
#Removes access to CodeIgniter system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#This last condition enables access to the images and css
#folders, and the robots.txt file
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php?/$1 [L]
If your using XAMPP on a local machine, your should use internal rather than mod_rewrite.
It will load your pages under the alias name.
it took me a while to figure that out - apparently you should use mod_rewrite on remote servers to achieve the same thing.
RewriteBase /
in your .htaccess should be
RewriteBase /app_name/
to specify which directory it is..
First, a question. Is your $system_folder variable really set to:
$system_folder = "#codeigniter";
or was that a nerf from the weird (to me) way SO uses markdown? If it is, remove the #. It is an invalid character for directory/file names.
Next, I believe your RewriteBase should be /, since you use an alias in Apache, but don't quote me on that.
I personally use the .htaccess format supplied here: CodeIgniter URLs in the User Guide; under the heading Removing the index.php file. There are many ways to do it, however. A quick Google search yields a couple thousand.
Do you have mod_rewrite enabled? Check the forum post here.

Categories